vue封装Tabel表格和Pagination分页

功能:传入封装的接口和参数,父组件通过调用里面的方法实现刷新和重载。

先封装个小功能组件

// 超出现实省略号,悬浮tootip提示
// cellExpand.vue
<template>
  <el-tooltip
    effect="dark"
    :content="contentHover"
    placement="top"
    :disabled="isShowTooltip"
  >
    <div class="overview_container" @mouseover="onMouseOver()">
      <span ref="name">{{ content }}</span>
    </div>
  </el-tooltip>
</template>

<script>
export default {
  props: {
    content: {
      default: ""
    }
  },
  data() {
    return {
      isShowTooltip: false,
      contentHover: ""
    };
  },
  methods: {
    onMouseOver() {
      const tag = this.$refs.name;
      const parentWidth = tag.parentNode.offsetWidth;
      const contentWidth = tag.offsetWidth;
      this.isShowTooltip = contentWidth <= parentWidth;
      this.contentHover = String(this.content);
    }
  }
};
</script>

<style type="text/css" scoped>
.overview_container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>

接下来开始封装我们的组件

// richDataTable.vue
<template>
  <div class="common-table">
    <el-table
      ref="table"
      :data="tableData.data"
      v-loading="tableData.loading"
      border
      highlight-current-row
      v-bind="tableProps"
      v-on="$listeners"
    >
      <el-table-column
        v-if="isCheckbox"
        :reserve-selection="!!tableProps['row-key']"
        type="selection"
        width="50"
      />
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        :align="item.align ? item.align : 'center'"
        v-bind="item"
      >
        <template slot-scope="scope">
          <slot :name="item.prop" :row="scope.row">
            <cell-expand
              :content="
                item.formatter
                  ? item.formatter(scope.row)
                  : scope.row[item.prop]
              "
            ></cell-expand>
          </slot>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      background
      v-if="showPage"
      @size-change="refresh"
      @current-change="refresh"
      :current-page.sync="pageConf.current"
      :page-sizes.sync="pageConf.pageOption"
      :page-size.sync="pageConf.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageConf.total"
      v-bind="paginationProps"
    >
    </el-pagination>
  </div>
</template>

<script>
export default {
  props: {
    tableProps: {
      type: Object,
      default: () => ({})
    },
    paginationProps: {
      type: Object,
      default: () => ({})
    },
    columns: {
      type: Array,
      default: () => []
    },
    isCheckbox: {
      type: Boolean,
      default: false
    },
    api: {
      type: Function,
      default: () => Promise.resolve()
    },
    params: {
      type: Object,
      default: () => ({})
    },
    showPage: {
      type: Boolean,
      default: true
    },
    reserveSelection: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      tableData: {
        data: [],
        loading: false
      },
      pageConf: {
        current: 1,
        size: 10,
        total: 0,
        pageOption: [10, 20, 50]
      }
    };
  },
  methods: {
    reload() {
      this.pageConf.current = 1;
      this.refresh();
    },
    refresh() {
      this.$nextTick(() => {
        const params = this.showPage
          ? { current: this.pageConf.current, size: this.pageConf.size }
          : {};
        this.tableData.loading = true;
        this.api({ ...this.params, ...params })
          .then(res => {
            if (this.showPage) {
              this.tableData.data = res.data.records;
              this.pageConf.total = res.data.total;
            } else {
              this.tableData.data = res.data;
            }
          })
          .finally(() => {
            this.tableData.loading = false;
          });
      });
    },
    reset() {
      this.tableData = {
        data: [],
        loading: false
      };
      this.pageConf = {
        current: 1,
        size: 10,
        total: 0,
        pageOption: [10, 20, 50]
      };
    }
  },
  computed: {
    tableRef() {
      return this.$refs.table;
    }
  }
};
</script>

<style lang="scss" scoped></style>

请求接口部分要和后端约定返回的格式!

使用demo

// api.js
export const api = (params) => axios.get('/getlist', {params: params})
}
// api.js
</template>
	<rich-data-table
        ref="richDataTable"
        :columns="columns"
        :api="api"
        :params="params"
      >
        <template slot-scope="scope" slot="action">
          <el-button type="text" @click="openDialog(scope.row)"
            >操作</el-button
          >
        </template>
      </rich-data-table>
 </template>
 import { api } from "./api";
 export default {
  data() {
    return {
      api,
      params: {
        destination: "",
        strFlightDate: "",
        endFlightDate: ""
      },
      columns: [
        { prop: "action", label: "操作", width: "80", fixed: true },
        { prop: "status", label: "货物状态", formatter: this.formatter, },
        { prop: "destination", label: "货物目的港" },
        { prop: "confirmPieces", label: "收货件数" },
        { prop: "confirmWeight", label: "收货重量" },
        { prop: "assembledPieces", label: "出港件数" },
        { prop: "assembledWeight", label: "出港重量" }
      ],
    };
  },
  methods: {
    handleSearch() {
      this.$refs["richDataTable"].reload();
    },
    formatter(row) {
      const DICT = {
        0: "未收单",
        1: "已收单"
      };
      return DICT[row.receiveStatus];
    },
  },
  mounted() {
    this.$refs["richDataTable"].reload();
  }
};
</script>
// 处理复杂的params
computed: {
    params() {
      const { flightIndex } = this.query;
      const { flightNo, flightDate } = this.flightNoList[flightIndex] || {};
      return {
        flightNo,
        flightDate
      };
    }
  },
// 允许用户多选,并且根据row-key设置勾选状态,使其不会随着切换分页而丢失
<rich-data-table
          ref="richDataTable"
          :columns="columns"
          :api="api"
          :params="params"
          :showPage="false"
          isCheckbox
          :tableProps="{ 'row-key': record => record.awbCode }"
          @selection-change="handleSelectionChange"
        />
  1. 当我们想使用插槽时需要注意插槽的名称需要和columns里对应的prop名称保持一致;
  2. 根据vue的生命周期,需要在mounted的生命周期中调用加载方法,在created中调用的话获取不到子组建的ref;
  3. 如果params参数比较复杂,涉及到业务逻辑,可以放到computed中处理,如上图所示;

结语

写惯了jsx想在columns里通过render方法自定义column,发现vue不支持,只能通过具名插槽的形式,希望有朋友可以给点优化建议。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值