vue3 封装table
时间: 2023-10-02 12:13:27 浏览: 34
Vue3 提供了 Composition API,可以更方便地进行组件封装。下面是一个简单的 Table 组件的封装示例:
```vue
<template>
<table>
<thead>
<tr>
<th v-for="column in columns" :key="column.field">{{ column.title }}</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="index">
<td v-for="column in columns" :key="column.field">{{ item[column.field] }}</td>
</tr>
</tbody>
</table>
</template>
<script>
import { reactive } from 'vue';
export default {
props: {
columns: {
type: Array,
required: true,
},
data: {
type: Array,
required: true,
},
},
setup(props) {
const state = reactive({
columns: props.columns,
data: props.data,
});
return {
columns: state.columns,
data: state.data,
};
},
};
</script>
```
在这个示例中,我们使用了 reactive 函数创建了一个响应式对象 state,然后将 props 中的 columns 和 data 属性赋值给 state 中的属性。通过返回 columns 和 data 属性,我们可以在模板中访问它们。
这个组件只提供了最基本的表格功能。如果需要更复杂的功能,可以考虑使用第三方表格组件库,例如 Element UI 或 Vuetify。