vue封装一个可自由选择展示列的表格
时间: 2024-03-21 18:19:33 浏览: 12
以下是一个简单的示例,展示如何使用Vue组件封装一个可自由选择展示列的表格。
```html
<template>
<div>
<div class="columns">
<label v-for="col in columns" :key="col">
<input type="checkbox" v-model="selectedColumns" :value="col">
{{ col }}
</label>
</div>
<table>
<thead>
<tr>
<th v-for="col in selectedColumns">{{ col }}</th>
</tr>
</thead>
<tbody>
<tr v-for="row in rows" :key="row.id">
<td v-for="col in selectedColumns">{{ row[col.toLowerCase()] }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
export default {
props: {
columns: {
type: Array,
required: true
},
rows: {
type: Array,
required: true
}
},
data() {
return {
selectedColumns: this.columns.slice()
}
}
}
</script>
```
在这个组件中,我们传递了两个props:columns和rows。columns是一个字符串数组,表示表格的列名;rows是一个对象数组,每个对象表示一行数据。
组件中的data包含一个selectedColumns数组,它被初始化为columns数组的一个拷贝。selectedColumns是用来保存用户选择的列名的数组。在组件中,我们使用v-model指令将每个列名的复选框与selectedColumns数组中的相应项绑定。
在表格中,我们使用v-for指令渲染列名和每行数据。在渲染列名时,我们只渲染selectedColumns数组中包含的列。在渲染每行数据时,我们只渲染selectedColumns数组中包含的列的数据。注意,我们将列名转换为小写,以便在行数据对象中找到相应的属性。
这个组件还有很多可以改进的地方,比如:添加排序、搜索和分页等功能。但是,它展示了如何使用Vue组件封装一个可自由选择展示列的表格。