(编辑:jimmy 日期: 2025/10/29 浏览:2)
前言
起因:
在使用 element-ui table组件时,由于表列比较多一个个写特别麻烦,所以想通过将所有表头定义成一个数组,通过遍历多方式去实现。这样解决了手写很多 el-table-column 的情况。
障碍:
类似于下面自定义表列的样式,它是通过 slot-scope 去覆盖 el-table-column 内部slot的样式实现的。那我们在遍历表头数组的时候如何实现呢?
参考:
用过 react 开发会经常用到 ant design ,其中它的 table 组件是可以接受 render属性的,下面使用table组件时,只需要定义好,columns(表头列) data(表的具体数据)即可。整体看起来很简洁 去渲染自定义的组件的。 点击查看 antdesign
demo:
codepen demo地址
const columns = [
{
title: 'Name',
dataIndex: 'name',
render: (text, row, index) => {
if (index < 4) {
return <a>{text}</a>;
}
return {
children: <a>{text}</a>,
props: {
colSpan: 5,
},
};
},
}]
const const data = [
{
key: '1',
name: 'John Brown',
age: 32,
tel: '0571-22098909',
phone: 18889898989,
address: 'New York No. 1 Lake Park',
}]
ReactDOM.render(<Table columns={columns} dataSource={data} bordered />, mountNode);
在 Vue 中实现 render 属性
接下来我们要实现下图的table的样式,但是这一次我们采用 render 传参数的方式
思路
子组件定义默认值
有了上面的思路,去实现子组件。我们需要知道一点,每个 el-table-column 只是定义了一列的表头和数据,而 :data="tableList" 中的每项值是定义了一行的数据。所以 el-table-column 是按列来分,data 是按行来分
<template>
<el-table :data="tableList" style="width:500px">
<template v-for="item in propList">
<slot :content="item">
<el-table-column :key="item.id" :prop="item.prop" :label="item.label"></el-table-column>
</slot>
</template>
</el-table>
</template>
<script>
export default {
props:{
propList:{
type:Array,
default:()=>[]
},
tableList:{
type:Array,
default:()=>[]
},
}
}
</script>
父组件定义
父组件通过 slot-scope 来接受到子组件传递过来的数据,然后判断是否有 render 属性来确定是否用要去自定义样式覆盖默认的 slot
最终通过 v-html 去解析生成的字符串模版
<slot-item :propList="propList" :tableList="tableList">
<template slot-scope="{content}" v-if="content.render">
<el-table-column :label="content.label">
<template slot-scope="{$index,row}">
<div v-html="content.render(row)"></div>
</template>
</el-table-column>
</template>
</slot-item>
export default {
components:{
SlotItem
},
data () {
return {
propList:[
{label:'姓名',prop:'name',id:1},
{label:'图片',prop:'pic',id:2,render:({pic})=>{
return `<img style="width:30px;height:30px" src='${pic}' />`
}},
{label:'操作',prop:'operate',id:3,render:({text})=>{
return `<div style="color:#999">${text}</div>`
}},
],
tableList:[
{name:'章三',pic:'https://zh-static-files.oss-cn-hangzhou.aliyuncs.com//karazhan/content/poster/2019/11/16e30c192f6.png',text:'新增'},
{name:'里斯',pic:'https://zh-static-files.oss-cn-hangzhou.aliyuncs.com//karazhan/content/poster/2019/11/16e30c2797e.png',text:'删除'},
{name:'网舞',pic:'https://zh-static-files.oss-cn-hangzhou.aliyuncs.com//karazhan/content/poster/2019/11/16e30c33144.png',text:'跳转'},
]
}
}
}
</script>
结尾
有了render属性,可以想 ant-design 那样简洁的属性 ui组件模版了!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。