二次封装element的分页组件

46 阅读1分钟
<template>
  <div v-if="_query.total != 0" class="pagination-box">
    <el-pagination
      @size-change="currentSizeChange"
      @current-change="currentChange"
      :current-page="_query.page"
      :page-sizes="pageSize"
      :page-size="_query.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="_query.total"
    >
    </el-pagination>
  </div>
</template>
  
  <script>
export default {
  name: "pagination",
  props: {
    query: {
      type: Object,
      default: () => {
        return {
          page: 1,
          pageSize: 10,
          total: 0,
        };
      },
    },
    pageSize: {
      type: Array,
      default: () => [10, 20, 30, 40],
    },
  },
  computed: {
    _query: {
      get() {
        return this.query;
      },
      set(n) {
        this.$emit("update:query", n);
      },
    },
  },
  watch: {
    "query.total": {
      async handler(n, v) {
        if (this.query.page != 1) {
          //忽略第一页
          if (n != 0) {
            if (n < v && n % this.query.pageSize == 0) {
              //删除条件下
              this.query.page -= await 1;
              this.$emit("change");
            }
          }
        }
      },
    },
  },
  methods: {
    currentChange(val) {
      this._query.page = val;
      this.$emit("change");
    },
    currentSizeChange(val) {
      //切换pageSize时组件自动将page重置为1,触发currentChange
      this._query.pageSize = val;
      if (this._query.page == 1) {
        this.$emit("change");
        //page为1时不会触发currentChange,需要主动触发列表刷新
      }
    },
  },
  mounted() {},
};
</script>
  
  <style scoped lang="scss">
.pagination-box {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
</style>