Vue高阶组件的应用场景一:el-table表格删除数据后,el-pagination自动向前翻页。

302 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1.删除最后一页全部数据时,删除成功后,分页组件需要自动往前翻页。 2.一次删除多页数据时,如删除之前,当前页在最后一页,删除成功之后,分页组件需要自动往前翻页。 3.只有1页时,自动隐藏分页组件。 AutoPageForward.js

export const AutoPageForward = function(Pagination) {
  return {
    props: {
      ...Pagination.props
    },
    watch: {
      total(newTotal) {
        if (
          this.currentPage > 1 &&
          this.currentPage * this.pageSize - newTotal >= this.pageSize
        ) {
          const newCurrentPage = Math.ceil(newTotal / this.pageSize) || 1;
          this.$listeners['current-change'](newCurrentPage);
        }
      }
    },
    render(h) {
      if (this.$props.total > this.$props.pageSize || this.$props.currentPage > 1) {
        return h(Pagination, {
          on: { ...this.$listeners },
          props: this.$props,
          attrs: this.$attrs,
          slots: this.$slots,
          scopedSlots: this.$scopedSlots
        });
      }
    }
  };
};

main.js

import ElementUI, { Pagination } from 'element-ui';
import { AutoPageForward } from '@/components/common/middleware/AutoPageForward.js';
Vue.use(ElementUI);
Vue.component(Pagination.name, AutoPageForward(Pagination));