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>
相关推荐
会豪12 小时前
Electron-Vite (一)快速构建桌面应用
前端
中微子12 小时前
React 执行阶段与渲染机制详解(基于 React 18+ 官方文档)
前端
唐某人丶12 小时前
教你如何用 JS 实现 Agent 系统(2)—— 开发 ReAct 版本的“深度搜索”
前端·人工智能·aigc
中微子12 小时前
深入剖析 useState产生的 setState的完整执行流程
前端
遂心_12 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
Gracemark13 小时前
高德地图-地图选择经纬度问题【使用输入提示-使用Autocomplete进行联想输入】(复盘)
vue.js
小徐_233313 小时前
uni-app vue3 也能使用 Echarts?Wot Starter 是这样做的!
前端·uni-app·echarts
RoyLin13 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
遂心_13 小时前
深入理解 React Hook:useEffect 完全指南
前端·javascript·react.js
Moonbit13 小时前
MoonBit 正式加入 WebAssembly Component Model 官方文档 !
前端·后端·编程语言