一、安装 element-plus
element-plus官网https://element-plus.org/zh-CN/
1、npm安装
npm install element-plus --save
2、yarn安装
yarn add element-plus
3、pnpm安装
pnpm install element-plus
4、main.ts导入(vue3)
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
app.use(ElementPlus)
二、封装table组件
// iot-table.vue
<template>
<el-table :data="data" :height="height" @selection-change="handleSelectionChange">
<el-table-column type="selection" width="55" />
<el-table-column
v-for="column in columns"
:key="column.prop"
:prop="column.prop"
:label="column.label"
:width="column.width"
:align="column.align"
:fixed="column.fixed"
:show-overflow-tooltip="column.showOverflowTooltip"
>
<template v-slot="scope">
<component :is="column.render" v-bind="scope" v-if="column.render"></component>
<span v-else>{{ scope.row[column.prop] }}</span>
</template>
</el-table-column>
</el-table>
</template>
<script lang="ts" setup>
interface TableColumn {
prop: string;
label: string;
width?: string | number;
align?: string;
fixed?: string | boolean;
render?: (scope: any) => any;
showOverflowTooltip?: boolean;
}
const props = defineProps<{
data: any[];
columns: TableColumn[];
height?: string | number;
}>();
const emit = defineEmits<{
(event: 'selection-change', selection: any[]): void;
}>();
const handleSelectionChange = (selection: any[]) => {
emit('selection-change', selection);
};
</script>
三、使用上面封装的表格
<template>
<iot-table :data="list" :columns="columns" @selection-change="handleSelectionChange" />
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElIcon, ElButton } from 'element-plus'; // 导入button按钮或者其他的组件
import IotTable from '@/components/iot-table.vue'; // 导入封装好的table组件
const list = ref<any>([]); // 后端返回数组,接口获取到
const selectedRows =ref<any>([]) // 多选数组
const columns = ref<any>([
{
prop: 'name',
label: '名字',
width: 140, // 列宽度
fixed: 'left', // 列固定
render: (scope: any) => {
// 判断后端返回的字段,可以用三元表达式,根据个人喜好
if (scope.row.name === 'lisi') {
return h('span', '李四')
} else {
return '张三';
}
},
},
{
prop: 'messageId',
label: '消息ID',
align: 'center',
width: 260,
render: (scope: any) => {
if (scope.row.messageId) {
return h(
ElTag, // el-tag组件,还可以添加任意其他组件,在上面导入即可
{
type: "primary",
effect: "plain",
},
{ default: () => scope.row.messageId }
)
}
}
},
{
prop: 'age',
label: '年龄',
align: 'center'
},
{
prop: 'operate',
label: '操作',
align: 'center',
fixed: 'right',
width: 180,
render: (scope: any) => {
// 两个按钮以上用数组包裹,单个去掉数组包裹
return [
h(
ElButton,
{
onClick: () => openDetail(scope.row),
type: 'warning',
disabled: false,
size: 'small',
icon: 'View',
round: false,
circle: false,
plain: false,
link: true
},
{ default: () => '详情' }
),
h(
ElButton,
{
onClick: () => handleUpdate(scope.row),
type: 'primary',
disabled: false,
size: 'small',
icon: 'Edit',
round: false,
circle: false,
plain: false,
link: true
},
{ default: () => '修改' }
)
]
}
},
]);
const handleSelectionChange = (selection: any[]) => {
selectedRows.value = selection.map(row => row.id);
};
</script>