一、目的
一般在后台控制台之类的项目中,表格和图标是应用最多的地方,我们今天来封装一个表格的公共组件,用起来非常的简单。
二、表格公共组件代码
// src/components/mytable.vue
<template>
<el-table
:data="tableData"
stripe
style="width: 100%">
<el-table-column v-for="col in tableConfig" :key="col.label" :type="col.type" :label="col.label" :prop="col.prop"
:align="col.align">
<template v-slot="scope" v-if="col.type === null">
<slot :name="col.name" v-if="col.slot" :row="scope.row"
:index="scope.$index"></slot>
<span v-else>{{ scope.row[col.prop] || '-' }}</span>
</template>
</el-table-column>
</el-table>
</template>
<script lang="ts">
import { defineComponent} from "vue";
export default defineComponent({
name:"mytable",
props:{
tableData:{
default(data:any){
return data
}
},
tableConfig:{
default(data:any){
return data
}
},
},
setup() {
return {}
},
components:{},
})
</script>
上面就是一个简单的展示用的表格,
缺点是不能展示深层数据。
下面说一下 如何使用
// 在其他组件中调用公共组件mytable
<template>
<div>
<mytable :tableData="tableData" :tableConfig="tableConfig">
<template v-slot:caozuo="shuju">
<el-button @click="caozuofunc(shuju.row.name)">操作</el-button>
</template>
</mytable>
</div>
</template>
<script lang="ts">
import {defineComponent, ref} from "vue";
import Mytable from "@/components/mytable.vue";
export default defineComponent({
name: "imagevue",
setup() {
const tableData = ref([
{
name: "sgsfsdfs",
content: "61561651",
},
{
name: "651651",
content: "sdfsdfsd",
},
])
const tableConfig = ref([
{type: "selection", align: "center"},
{type: "index", align: "center"},
{type: null, prop: "name", align: "center", label: "名字"},
{type: null, prop: "content", align: "center", label: "内容"},
{type: null, slot: true, name: "caozuo", label: "操作"},
])
function caozuofunc(name: string) {
console.log(name, "name")
}
return {
tableData,
tableConfig,
caozuofunc,
}
},
components: {
Mytable
},
})
</script>
{type: “selection”, align: “center”}, // 选择框
{type: “index”, align: “center”}, // 序号
{type: null, prop: “name”, align: “center”, label: “名字”}, // 普通内容
{type: null, prop: “content”, align: “center”, label: “内容”}, // 普通内容
{type: null, slot: true, name: “caozuo”, label: “操作”}, // 插槽,具名插槽,必须有name属性
template v-slot:caozuo=“shuju” 这里的shuju,就是我们给slot绑定的数据name,index,row
也就是说,你绑定了什么,就可以直接使用什么,比如shuju.index,shuju.row。
也可以直接解构, template v-slot:caozuo="{row,name,index}"
如果给mytable加上ref,就可以直接获取组件内的被选中的数据。
还可以扩展其他属性 ,比如fit,比如width等等,
本文介绍如何在Vue.js项目中封装一个简洁易用的表格公共组件,该组件适用于后台控制台等场景,但不支持深层数据展示。通过示例代码展示了组件的使用方法,包括设置表格列配置,如选择框、序号、普通内容和具名插槽,并提供了在其他组件中调用公共组件的模板结构,以及如何通过插槽实现操作列的功能。
713

被折叠的 条评论
为什么被折叠?



