vue2 elementui 封装一个动态表格复杂组件

在 Vue 2 和 Element UI 中封装一个动态表格组件意味着要创建一个组件,它能够根据传入的数据和配置动态地生成表格,并支持排序、筛选、分页等功能。以下是一个基本的示例,展示了如何创建一个这样的动态表格组件:

首先,确保你已经安装了 Element UI,并在你的 Vue 项目中正确地引入和使用了它。

然后,创建一个新的 Vue 组件,比如 DynamicTable.vue

复制代码
<template>
  <el-table
    :data="tableData"
    style="width: 100%"
    @sort-change="handleSortChange"
  >
    <el-table-column
      v-for="(column, index) in columns"
      :key="index"
      :prop="column.prop"
      :label="column.label"
      :sortable="column.sortable"
      :filters="column.filters"
      :filter-method="column.filterMethod"
    >
    </el-table-column>
  </el-table>
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalItems">
  </el-pagination>
</template>

<script>
export default {
  name: 'DynamicTable',
  props: {
    columns: {
      type: Array,
      required: true,
    },
    data: {
      type: Array,
      required: true,
    },
  },
  data() {
    return {
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      sort: {
        prop: '',
        order: '',
      },
      totalItems: 0,
    };
  },
  computed: {
    filteredData() {
      if (!this.sort.prop) return this.data;
      return this.data.sort((a, b) => {
        if (a[this.sort.prop] < b[this.sort.prop]) return this.sort.order === 'ascending' ? -1 : 1;
        if (a[this.sort.prop] > b[this.sort.prop]) return this.sort.order === 'ascending' ? 1 : -1;
        return 0;
      });
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = this.currentPage * this.pageSize;
      return this.filteredData.slice(start, end);
    },
  },
  watch: {
    data(newData) {
      this.totalItems = newData.length;
      this.tableData = newData.slice();
    },
  },
  methods: {
    handleSortChange({ column, prop, order }) {
      this.sort.prop = prop;
      this.sort.order = order;
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },
  },
  mounted() {
    this.tableData = this.data.slice();
  },
};
</script>

<style scoped>
/* 你可以在这里添加一些自定义的样式 */
</style>
相关推荐
coder_pig21 分钟前
跟🤡杰哥一起学Flutter (三十四、玩转Flutter手势✋)
前端·flutter·harmonyos
万少28 分钟前
01-自然壁纸实战教程-免费开放啦
前端
独立开阀者_FwtCoder30 分钟前
【Augment】 Augment技巧之 Rewrite Prompt(重写提示) 有神奇的魔法
前端·javascript·github
yuki_uix40 分钟前
AI辅助网页设计:从图片到代码的实践探索
前端
我想说一句41 分钟前
事件机制与委托:从冒泡捕获到高效编程的奇妙之旅
前端·javascript
陈随易41 分钟前
MoonBit助力前端开发,加密&性能两不误,斐波那契测试提高3-4倍
前端·后端·程序员
小飞悟1 小时前
你以为 React 的事件很简单?错了,它暗藏玄机!
前端·javascript·面试
中微子1 小时前
JavaScript 事件机制:捕获、冒泡与事件委托详解
前端·javascript
Whoisshutiao1 小时前
网安-XSS-pikachu
前端·安全·网络安全
惊鸿2871 小时前
Taro3+小程序Canvas动态生成海报和二维码分享到朋友圈
前端