element-ui table组件如何使用render属性的实现

2020-06-12 20:52:16易采站长站整理

<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

首先看传递给子组件的表头数据,可以看到,第二,三行列表中有一个render属性,它是一个函数并返回一个 html 的字符串。
tableList就是普通的数据,也就是数据的 key 值去渲染对应的数据
图片这列举例子,当父组件通过 props 将 {label,prop,id,render} 传递给子组件后,子组件有通过 slot 将值传递回父组件。

到这里有些人会有疑问,为什么要将数据这样传来传去,因为我们在子组件中定义好了默认样式,而父组件中需要判断该值是否需要自定义样式,去覆盖子组件中的样式。
这些自定义样式就是一开始,在render函数中返回的 html 字符串
为啥 React 直接返回 jsx ,而Vue需要返回 html 字符串,因为react本身就是使用 JSX 来渲染模版的,最终都会通过 babel 编译成 React.createElement ,而Vue是通过 template 来渲染模版的,这里通过定义 template 模版字符串,最终通过 v-html 来解析

为什么这里有两个 slot-scope ,第一个是 slot-item 的,组件内部通过 slot-scope 将值传递出来。而第二个是 el-table-item 的,ui组件内部同样将数据通过 slot-scope 传递传来。
通过第一个 slot-scope 拿到 propList 中的定义的 render 函数,通过第二个 slot-scope 拿到 table 组件内部传递出来的数据,将数据传递给 render 函数去生成自定义模版

最终通过 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})=>{