el-pagination分页组件结合路由自定义封装

el-pagination query router

封装原因

  • 单纯使用 el-pagination 时,刷新页面无法记住页码信息,需要将页码和条数放在url的?后面,如?current=1&size=10
  • 刷新页面时需要读取url后面参数,并进行分页请求
  • 页码信息改变时需要先设置url后面的参数,再进行分页请求
  • 分页应该和业务隔离

解释

分页是项目中的最常见的功能之一,前后端分离后,一般由客户端发起分页请求,请求需要携带
当前页码和分页个数。比如请求为 api?current=1&size=10 时,代表请求第
一页数据,并且每页10条数据。

封装组件

<template>
  <el-pagination
    background
    :current-page="current"
    :page-sizes="pageSizes"
    :page-size="size"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />
</template>

<script>
export default {
  name: 'MyPagination',
  props: {
    fetchList: {
      type: Function,
      default: null
    },
    total: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      current: 1,
      size: 10,
      pageSizes: [5, 10, 20, 50],
      query: ''
    }
  },
  methods: {
    handleSizeChange(val) {
      this.size = val
      this.querySetter()
    },
    handleCurrentChange(val) {
      this.current = val
      this.querySetter()
    },
    queryGetter() {
      let current = parseInt(this.$route.query.current)
      if (!current || current <= 0) {
        current = 1
      }
      this.current = current
      let size = parseInt(this.$route.query.size)
      if (this.pageSizes.indexOf(size) === -1) {
        size = 10
      }
      this.size = size
    },
    querySetter() {
      const current = this.current
      const size = this.size
      this.$router.push({
        query: {
          current: current,
          size: size
        }
      })
      this.query = `current=${current}&size=${size}`
    },
    pageInit() {
      this.queryGetter()
      this.querySetter()
    }
  },
  created() {
    this.pageInit()
  },
  watch: {
    query() {
      if (this.fetchList) {
        this.fetchList(this.current, this.size)
      }
    }
  }
}
</script>

使用

<template>
  <ul>
    <li v-for="item in list">{{item}}</li>
  </ul>
  <MyPagination :total="total" :fetchList="fetchData"></MyPagination>
</template>

<script>
export default {
  components: { MyPagination },
  data() {
    return {
      total: 0,
      list: []
    }
  },
  methods: {
    fetchData(current, size) {
      //伪代码
      ajax({
        url: 'xxx',
        method: 'get',
        params: {
          current: current,
          size: size
        }
      }).then(response => {
        this.list = response.list
        this.total = response.total
      })
    }
  }
}
</script>

使用说明

自定义组件 MyPagination 接收两个参数,一个是数据总条数 total,
一个是分页请求方法 fetchList,该方法有两个参数,
第一个是当前页码 current,第二个是每页条数 size,
fetchList方法中的ajax数据回调里,需要给total和数据列表赋值

不积跬步无以至千里
原文地址:https://www.cnblogs.com/xiaogblog/p/14388976.html