一、封装表格组件
javascript
复制代码
<template>
<el-table :data="list" :default-sort="{ prop: 'date' }" style="width: 100%">
<template v-for="item in tableColumn">
<el-table-column
v-if="item.filters"
:prop="item.prop"
:label="item.label"
:sortable="item.sortable"
:filters="item.filters"
:filter-method="filterHandler(item.filterMethod)"
/>
<el-table-column
v-if="!item.filters"
:prop="item.prop"
:label="item.label"
:sortable="item.sortable"
/>
</template>
</el-table>
</template>
<script scoped>
export default {
data() {
return {
list: [],
tableColumn: [],
};
},
props: {
data: {
type: Array,
default: [],
},
column: {
type: Array,
default: [],
},
},
watch: {
data: {
immediate: true,
deep: true,
handler(val) {
if (val.length) {
this.list = JSON.parse(JSON.stringify(val));
}
},
},
column: {
immediate: true,
deep: true,
handler(val) {
if (val.length) {
this.tableColumn = JSON.parse(JSON.stringify(val));
}
},
},
},
methods: {
// 如果没传,那么默认等值判断
filterHandler(filterMethod) {
if (filterMethod) {
return item.filterMethod;
} else {
return (value, row, column) => {
const property = column["property"];
return row[property] === value;
};
}
},
},
};
</script>
二、使用方法
javascript
复制代码
<template>
<div id="app"><Tabel :data="data" :column="column" /></div>
</template>
<script>
import Tabel from "@/components/Tabel.vue";
export default {
components: { Tabel },
data() {
return {
column: [
{
label: "日期",
prop: "date",
sortable: true,
},
{
label: "姓名",
prop: "name",
filters: [{ text: "王小龙", value: "王小龙" }],
},
{
label: "地址",
prop: "address",
},
],
data: [
{
date: "2016-05-02",
name: "王小猪",
address: "上海市普陀区金沙江路 1518 弄",
},
{
date: "2016-05-04",
name: "王小虎",
address: "上海市普陀区金沙江路 1517 弄",
},
{
date: "2016-05-01",
name: "王小龙",
address: "上海市普陀区金沙江路 1519 弄",
},
{
date: "2016-05-03",
name: "王小海",
address: "上海市普陀区金沙江路 1516 弄",
},
],
};
},
};
</script>