最简单的分页组件-基于 elementui 的分页二次封装

背景

一般表格比较多的项目中,多会涉及到分页和条件检索。

如果每个表格单独配置一个分页,后期维护起来比较繁琐,而且,写代码也是copy来copy去,十分烦恼。

因此,基于elementui 的分页组件的二次封装就应时而生了。

子组件代码

在分页子组件中,我只关心当前页是第几页,以及共有多少页。
很显然,默认的分页,当前页肯定是第一页,而共有多少页,需要看后台返回的数据总数量,除以每页显示的数据量
简单来说,就是Math.ceil(count / pageSize)

下面是分页组件具体的代码。

<template>
  <el-pagination
    background
    layout="slot, prev, pager, next"
    :current-page.sync="currentPage"
    :page-size="pageSize"
    prev-text="上一页"
    next-text="下一页"
    :total="count"
    @current-change="handleCurrentChange"
  >
    <span v-html="`共 ${count} 条 &nbsp;&nbsp;&nbsp; 共 ${pages} 页`" />
  </el-pagination>
</template>

<script>
export default {
    
    
  props: {
    
    
    count: {
    
      // 数据总量
      type: Number,
      default: 0
    }
  },
  data() {
    
    
    return {
    
    
      pageSize: 10,  // 每页显示多少条数据
      currentPage: 1  // 默认当前页显示第一页
    }
  },
  computed: {
    
    
    pages() {
    
      // 计算共多少页
      return Math.ceil(this.count / this.pageSize)
    }
  },
  methods: {
    
    
    handleCurrentChange(page) {
    
      // 点击页码事件,通知父组件
      this.$emit('pageEvent', this.currentPage)
    }
  }
}
</script>

这样,一个子组件就完成了。

下面看看如何在父组件中使用。

在父组件中的使用

<template>
<div>
	<div class="search-wraper">
		<span>输入查找:</span>
		<el-input v-model="searchKey" />
		<el-button @click="fetchData">查询</el-button>
	</div>
	<div>
		<el-table v-loading="loading" :data="data"/>
		<my-pagination :count="count" @pageEvent="fetchData" />
	</div>
</div>
</template>
<script>
// 首先,我们先引入这个子组件,并在父组件中注册
import myPagination from '@/components/page/index'
import {
    
     getLog } from '@/api/user'
export default {
    
    
  components: {
    
     myPagination },
  data(){
    
    
	return {
    
    
		searchKey: '',
		loading: true,
		page: 1,
		data: [],
		count: 0
	}
  },
  methods: {
    
    
    fetchData(currentpage) {
    
    
      if (typeof currentpage === 'number') {
    
     // 切换页码
        this.page = currentpage
      } else {
    
     // 在输入检索条件进行查询的时候,将当前页设置为 1
        this.page = 1
      }
      const {
    
     page, searchKey } = this
      getLog({
    
     page, searchKey }).then(r => {
    
    
        this.data = r.results
        this.count = r.count
      }).catch().finally(this.loading = false)
    }
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/zhai_865327/article/details/112223998