vue3 使用element-plus 如何再次封装table组件
在Vue 3中,你可以通过再次封装Element Plus的<el-table>
组件来创建一个更高级的table组件。以下是一个简单的例子:
- 创建一个新的组件文件
MyTable.vue
。 - 在
MyTable.vue
中,导入el-table
和其他你想要使用的Element Plus组件,并注册它们。 - 提供props来接收外部传递的数据和配置选项。
- 使用
el-table
和相关组件,并将props中的数据和配置传递给它们。
<template>
<el-table :data="tableData" border style="width: 100%">
<el-table-column
v-for="column in columns"
:key="column.prop"
:prop="column.prop"
:label="column.label"
></el-table-column>
</el-table>
</template>
<script setup>
import { ElTable, ElTableColumn } from 'element-plus';
import { ref } from 'vue';
const props = defineProps({
columns: {
type: Array,
required: true
},
data: {
type: Array,
required: true
}
});
const tableData = ref(props.data);
</script>
- 在父组件中使用
MyTable
组件,并传递所需的列定义和数据。
<template>
<MyTable :columns="tableColumns" :data="tableData" />
</template>
<script setup>
import MyTable from './MyTable.vue';
const tableColumns = [
{ label: 'Date', prop: 'date' },
{ label: 'Name', prop: 'name' },
{ label: 'Address', prop: 'address' }
];
const tableData = [
{ date: '2016-05-02', name: 'John', address: 'No. 189, Grove St, Los Angeles' },
// ... more data
];
</script>
确保你已经安装了element-plus
,并在你的主入口文件(通常是main.js
或main.ts
)中进行了引入和全局注册。
import { createApp } from 'vue';
import App from './App.vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
const app = createApp(App);
app.use(ElementPlus);
app.mount('#app');
这样,你就创建了一个可以重复使用的MyTable
组件,它封装了Element Plus的<el-table>
组件,并允许通过props传递配置和数据。
评论已关闭