vue3+el-table组件二次封装
因为业务不是很复杂,所以做了简单的表格封装,满足了大多数后台管理页面的表格内容,其实还可以将page组件也封装进去,这里没做,后面会考虑加进去的
组件内容
<template>
<!-- 表格组件 -->
<div style="margin: 20px 0;">
<el-table style="width: 100%" :header-cell-style="{ backgroundColor: '#cdd6df', color: '#000' }"
v-bind="$attrs" ref="elTableRef" @selection-change="selectionChange">
<el-table-column v-if="selection" type="selection" width="55" :reserve-selection="true"
label="选择"></el-table-column>
<el-table-column v-if="index" type="index" width="55" label="序号"></el-table-column>
<el-table-column v-for="item in colunm" :prop="item.prop" :label="item.label" :width="item.width?item.width:''">
<template #default="scope">
<slot v-if="item.slot" :name="item.slot" :scope="scope"></slot>
<span v-else>{{ scope.row[item.prop] }}</span>
</template>
</el-table-column>
</el-table>
</div>
</template>
<script setup>
import { ref } from 'vue'
const props = defineProps({
colunm: {//表头数据
type: Array,
default: [
{
prop: "name",
label: "姓名",
},
{
prop: "sex",
label: "性别",
slot: "sex"
},
{
prop: "status",
label: "状态",
slot: "status"
},
]
},
index: {//是否首列索引
type: Boolean,
default: false
},
selection: {//是否首列可选
type: Boolean,
default: false
},
})
// 抛出事件:选择项变化;页面变化
const emits = defineEmits(["selectionChange"])
// 暴露el-table组件,使父组件通过 父组件Ref.value.element.方法名 来获取并使用el-table组件的方法
const elTableRef = ref(null)
defineExpose({ element: elTableRef })
const selectionChange = (selection) => {
emits("selectionChange", selection)
}
</script>
<style lang="scss" scoped></style>
页面调用
<myTable ref="tableRef" :data="dataArr" :colunm="cols" selection @selection-change="slecChange">
// 插槽内容:常见的比如状态:不同的状态需要不同的文字颜色;操作列:需要编辑删除等按钮
<template #status="scope">
<el-text type="warning" v-if="scope.scope.row.status == 0">发布中</el-text>
<el-text type="success" v-if="scope.scope.row.status == 1">使用中</el-text>
<el-text type="info" v-if="scope.scope.row.status == 3">已停用</el-text>
</template>
<template #actions="scope">
<el-button type="primary" link @click="openDialog">详情</el-button>
<el-button type="primary" link>停用</el-button>
<el-button type="primary" link>删除</el-button>
</template>
</myTable>
//在script中引入组件
import myTable from '组件路径'
//在script中使用el-table上的方法
//tableRef是二次封装后的组件的实例,element是el-table组件通过defineExpose暴露的组件实例
tableRef.value.element.clearSelection()//清空列表选项
要点
$attrs
通过v-bind绑定$attrs透传属性,使el-table上的属性无需通过prpos定义,也可以在封装好的组件上直接使用el-table的各种属性。
defineExpose
将模板中通过ref声明的组件暴露出去,使该组件上的方法能够被外部组件所用
插槽
通过props中的表头数据column中的每一项定义slot属性来生成同名插槽,当需要通过改变该列的内容或样式时,通过同名插槽来改写样式,通过scope.scope.row.表头数据中的prop值来获取该位置的值