vue实现动态columns
Vue 实现动态 columns 的方法
使用 v-for 动态渲染表格列
通过 v-for 指令可以动态渲染表格的列,columns 数据可以来自组件的 props 或 data。
<template>
<table>
<thead>
<tr>
<th v-for="column in columns" :key="column.key">
{{ column.title }}
</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td v-for="column in columns" :key="column.key">
{{ item[column.dataIndex] }}
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
columns: {
type: Array,
required: true
},
data: {
type: Array,
required: true
}
}
}
</script>
动态修改 columns 数据
可以通过方法动态修改 columns 数据,实现列的增删改查。
methods: {
addColumn() {
this.columns.push({
key: 'newColumn',
title: 'New Column',
dataIndex: 'newColumn'
})
},
removeColumn(key) {
this.columns = this.columns.filter(column => column.key !== key)
}
}
使用计算属性处理动态列
计算属性可以用于对 columns 数据进行处理,例如过滤、排序等。
computed: {
filteredColumns() {
return this.columns.filter(column => !column.hidden)
}
}
结合插槽实现更灵活的列渲染
使用插槽可以自定义列的渲染方式,提供更大的灵活性。
<template>
<table>
<thead>
<tr>
<th v-for="column in columns" :key="column.key">
<slot :name="`header-${column.key}`" :column="column">
{{ column.title }}
</slot>
</th>
</tr>
</thead>
<tbody>
<tr v-for="item in data" :key="item.id">
<td v-for="column in columns" :key="column.key">
<slot :name="`cell-${column.key}`" :item="item" :column="column">
{{ item[column.dataIndex] }}
</slot>
</td>
</tr>
</tbody>
</table>
</template>
使用第三方组件库
许多 Vue 组件库如 Element UI、Ant Design Vue 等提供了动态 columns 的功能。
<template>
<el-table :data="data">
<el-table-column
v-for="column in columns"
:key="column.key"
:prop="column.dataIndex"
:label="column.title"
/>
</el-table>
</template>
响应式 columns
结合 Vue 的响应式特性,columns 的变化会自动触发视图更新。
watch: {
columns: {
handler(newVal) {
console.log('Columns changed', newVal)
},
deep: true
}
}






