【vue3基础】Element-plus的分页组件封装

1,009 阅读1分钟

Element-plus 的分页组件默认是英文的,需要转为中文,传参也比较多,单独封装一下,使用起来简单,代码也简洁。

1. 创建 pagination 组件

<template>
  <div class="pagination-container">
    <el-config-provider :locale="zhCn">
      <el-pagination 
          v-model:current-page="currentPage" 
          v-model:page-size="pageSize" 
          size="default"
          layout="total, sizes, prev, pager, next, jumper" 
          :total="total" 
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange" 
          :page-sizes="pageSizes"
      />
    </el-config-provider>
  </div>
</template>

<script setup>
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
const props = defineProps({
  total: {
    type: Number,
    default: 0,
  },
  page: {
    type: Number,
    default: 1,
  },
  limit: {
    type: Number,
    default: 20,
  },
  pageSizes: {
    type: Array,
    default() {
      return [10, 20, 50, 100, 200, 500]
    }
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  size: {
    type: String,
    default: 'default'
  }
})

const emit = defineEmits()

const currentPage = computed(() => props.page)
const pageSize = computed(() => props.limit)

const handleCurrentChange = (val) => {
  emit('pagination', { page: val, limit: pageSize.value })
}

const handleSizeChange = (val) => {
  emit('pagination', { page: currentPage.value, limit: val })
}
</script>

2. 注册封装的分页插件

// main.js

// 引入分页组件
import Pagination from '@/components/Pagination.vue'
app.component('Pagination', Pagination)

3. 页面使用

<template>
    <Pagination 
        :total="total" 
        :page.sync="listParams.page" 
        :limit.sync="listParams.size"
        @pagination="getList"
    />
</template>

<script setup>
let listParams = reactive({
  page: 1,
  size: 20
})
let total = ref(0)

const getList = val => {
  if (val) {
    // 分页组件改变的时候会传递这个值
    listParams.page = val.page
    listParams.size = val.limit
  }
  ...
  ...
  // 调用接口赋值
}

</script>

4. 前后效果

封装前 QQ截图20241224110956.png

封装后

封装后1.png

个人感觉这样代码会更简洁一点,根据个人喜好使用。