后台管理经常会用到表格,一开始封装了一个常用的功能性表格,点击这里;
后来由于需求增加,在表格中还会用到switch,select,input等多种组件,每次都要在html中增加<el-table-column></el-table-column>, 维护起来相当麻烦,就想到了使用render渲染。
组件内部封装代码:
<template> <el-table :data="tableData" size="medium" fit :header-cell-style="{height: ‘40px‘,padding: ‘0‘,background: ‘#f7f9fa‘,‘font-size‘: ‘12px‘,color: ‘#8590a6‘}" :row-style="{‘font-size‘: ‘12px‘,color: ‘#212121‘}" ref="multipleTable" border stripe @sort-change="handleSort" @filter-change="filterHandler" @row-click="handleRowClick"> <el-table-column v-for="(th, key) in tableHeader" :key="key" :prop="th.prop" :label="th.label" :fixed="th.fixed" :sortable="th.sortable?‘custom‘:false" :filters="th.filters" :column-key="th.columnKey" :filtered-value="th.filteredValue" :filter-multiple="th.filterMultiple" :min-width="th.minWidth" align="center"> <template slot-scope="scope"> <ex-slot v-if="th.render" :render="th.render" :row="scope.row" :index="scope.$index" :column="th" /> <span v-else>{{ scope.row[th.prop] || ‘-‘ }}</span> </template> </el-table-column> </el-table> </template> <script> // 自定义内容的组件 var exSlot = { functional: true, props: { row: Object, render: Function, index: Number, column: { type: Object, default: null } }, render: (h, data) => { const params = { row: data.props.row, index: data.props.index } if (data.props.column) params.column = data.props.column return data.props.render(h, params) } } export default { name: ‘comp-table‘, components: { exSlot }, props: { // 表格数据 tableData: { type: Array, default: function () { return [] } }, // 表头数据 tableHeader: { type: Array, default: function () { return [] } } }, methods: { // 排序事件 handleSort (sort) { this.$emit(‘sort-events‘, sort) }, // 筛选事件 filterHandler (filters) { this.$emit(‘filter-events‘, filters) }, // 某一行被点击 handleRowClick (row) { this.$emit(‘click-events‘, row) } } } </script>
在模板中引用:
<template> <compTable :tableHeader="tableHeader" :tableData="tableData" @sort-events="handleSort" @filter-events="filterHandler" @click-events="handleClick" /> </template> <script> import compTable from ‘@/components/compTable‘ export default { components: { compTable }, data () { return { // 数据结构 tableData: [], // 为请求到的table数据 tableHeader: [ // 表头信息,可根据minWidth修改宽度 { prop: ‘uid‘, label: ‘订单号‘, minWidth: ‘160px‘ }, { prop: ‘peopleNumber‘, label: ‘人数‘, sortable: ‘custom‘, minWidth: ‘75px‘ }, { prop: ‘source‘, label: ‘来源‘, filters: sourceData, columnKey: ‘sourceList‘, minWidth: ‘90px‘, render: (h, params) => {return h(‘span‘,params.row.source) } } } } } </script>
原文地址:https://www.cnblogs.com/puerile/p/11897356.html
时间: 2024-10-10 20:10:38