关于分页的实践

/ vuewebgin / 没有评论 / 162浏览

环境

前端 vue + Element ui + axios

后端 Gin + Gorm

效果

原理

前端代码

<template>
  <div >
    <!--    <el-button type="success">{{userInfo.nickname}}</el-button>-->
    <el-row class="tac">
      <el-col :span="4">
      </el-col>
      <el-col class="content-right" :span="24">
        <el-card shadow="always">
          <el-table
            v-loading="loading"
            element-loading-text="🐱 喵~ 玩命加载中..."
            element-loading-spinner="el-icon-loadeding"
            element-loading-background="rgba(0, 0, 0, 0.6)"
            :default-sort = "{prop: 'UpdatedAt', order:'descending'}"
            :highlight-current-row=true
            :stripe=true
            :show-header=true
            :header-cell-style="{background:'#bfeeee',color:'#1b1f1e'}"
            :data="receiverInfos" style="width: 100%">
            <el-table-column
              :show-overflow-tooltip="true"
              label="文件名字"
              prop="FileName">
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              label="服务器路径"
              prop="FileServerPath">
            </el-table-column>
            <el-table-column
              :show-overflow-tooltip="true"
              label="更新时间"
              prop="UpdatedAt">
            <el-table-column
              align="right">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[5, 10, 20, 40]"
              :page-size="pagesize"
              layout="total, sizes,prev, pager, next"
              :total="total"
              prev-text="上一页"
              next-text="下一页">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Vue from "vue"
Vue.prototype.$http = require("axios")

export default {
  data() {
    return {
      loading:false,
      receiverInfos: [],
      currentPage: 1, //默认显示页面为1
      pagesize: 10, //    每页的数据条数
      total:0
    };
  },
  created() {
    // 获取当前登录的用户信息
    this.userInfo = JSON.parse(localStorage.getItem("userInfo") || "{}");
    this.getReceiverInfos();
  },
  methods: {
    //每页下拉显示数据
    handleSizeChange: function(size) {
      this.pagesize = size;
      this.getReceiverInfos()
    },
    //点击第几页
    handleCurrentChange: function(currentPage) {
      this.currentPage = currentPage;
      // alert(currentPage)
      this.getReceiverInfos()
    },
    // axios
    getReceiverInfos() {
      this.loading=true
      this.$http({
        method: "get",
        url: "/api/GetUploadInfo",
        params: {
          currentpage: this.currentPage,
          pagesize:this.pagesize
        },
      })
    .then(result => {
          this.loading=false
          this.total = result.data.total;
          this.receiverInfos = result.data.data;
          // console.log("接受的收据----- debug")
          // console.log(this.receiverInfos)
        })
        .catch(err => {
          console.dir(err);
        });
    },
    handleDelete(index, row) {
      this.$confirm('即将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //点击确定的操作(调用接口)
        return this.$http
          .post("/api/DelUploadInfo",
            {
              id:row.ID,
              serverfilename:row.FileServerPath
            },
          )
          .then(result => {
            // 删除成功提醒用户
            if (result.data.code === 20011){
              this.$message({
                message: row.FileName+" 删除成功 🐱~  ",
                type: "success"
              });
              this.receiverInfos.splice(index, 1);
            } else {
              this.$message({
                message: result.data.ServerFilePath+"   "+" 删除失败!" ,
                type: "error"
              });
            }
          })
          // 但是如果失败了也会报错, 通过.catch也可以进行捕获
          .catch(err => {
            // console.log(error.response.data.errMsg);
            this.$message.error("删除文件失败! 🐱");
          });
      }).catch(() => {
        //几点取消的提示
        this.$message.success("取消成功 🐱");
      });
    }
  }
};
</script>

<style lang="less" scoped>
</style>

后端 api

func GetUploadInfo(c *gin.Context) {
	// get 前端 当前页面 每页多少行,url传参的形式
	var pagesize string
	pagesize = c.Query("pagesize")
	var currentpage string
	currentpage = c.Query("currentpage")
	currentpageInt, _ := strconv.Atoi(currentpage)
	pagesizeInt, _ := strconv.Atoi(pagesize)
	var FileUpload_R_DB []model.FileUpload
	var total int
  // 求该表的和,返回给前端,前端自动根据总条数去布局
	model.DB.Find(&FileUpload_R_DB).Count(&total)
	//logrus.Error(total)
	if err := model.DB.Order("updated_at desc").Limit(pagesizeInt).Offset((currentpageInt - 1) * pagesizeInt).Find(&FileUpload_R_DB).Error; err != nil {
		c.JSON(500, gin.H{
			"code":  e.ERR_DB_R,
			"data":  err,
			"msg":   e.GetMsg(e.ERR_DB_R),
			"total": total,
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code":  e.SUCCESS,
			"data":  FileUpload_R_DB,
			"msg":   e.GetMsg(e.SUCCESS),
			"total": total,
		})
	}
}