因为表格数据比较同构,有时候列配置是动态的,此时但愿使用v-for来配置columnhtml
<template> <el-table :data="tableData"> <el-table-column v-for="col in columns" :key="col.dataIndex" :label="col.title" :prop="col.dataIndex" :formatter="col.render" /> </el-table> </template> <script> const PHONE_COLS = [ { title: '录音id', dataIndex: 'attach_id' }, { title: '接听客服', dataIndex: 'handle_user_info' }, { title: '呼叫类型', dataIndex: 'type_desc' }, { title: '通话时长', dataIndex: 'duration' }, ]; const WORK_COLS = [ { title: '工单id', dataIndex: 'attach_id' }, { title: '建立客服', dataIndex: 'handle_user_info' }, { title: '建立时间', dataIndex: 'c_t' }, { title: '工单来源', dataIndex: 'source' }, { title: '工单分类', dataIndex: 'ws_type', render: (row, column, cell) => (cell || []).join(',') } ]; export default { data () { return { columns: PHONE_COLS, tableData: [], tableTotal: 0, } }, } </script>
能够看到代码比直接使用template更加简洁,另外也能够利用formatter
函数处理简单的自定义字符串vue
template
的列当咱们但愿使用配置的方式来达到<template v-slot>
的效果,须要借助于vue
的render
函数与jsx
模板node
jsx
引入方法详见
渲染函数 & JSX
此时全部想建立vnode的时候均可以借助jsx
来实现,jsx
编译须要一个createElement
方法,以下react
// h就是createElement function render(h) { var a = 'test' return ( <el-tooltip class="item" effect="dark"> {a} </el-tooltip> ) }
table的formatter
方法也支持返回vnode渲染,所以咱们能够想办法拿到createElement
后使用jsx来达到复杂列的渲染,以下git
<template> <el-table :data="tableData"> <el-table-column v-for="col in columns" :key="col.dataIndex" :label="col.title" :prop="col.dataIndex" :formatter="col.render" /> </el-table> </template> <script> let createElement const WORK_COLS = [ { title: '工单id', dataIndex: 'attach_id' }, { title: '建立客服', dataIndex: 'handle_user_info' }, { title: '建立时间', dataIndex: 'c_t' }, { title: '工单来源', dataIndex: 'source' }, { title: '工单分类', dataIndex: 'ws_type', render: (row, column, cell) => (cell || []).join(',') }, { title: '工单描述', dataIndex: 'desc', render: (row, column, cell) => { return (function(h) { return ( <div domPropsInnerHTML={cell}></div> ); })(createElement) } }, ]; export default { data () { return { columns: WORK_COLS, tableData: [], tableTotal: 0, } }, mounted() { createElement = this.$createElement } } </script>
说明github
jsx
模板,咱们制造了带有h函数的匿名函数来生成vnodeNote the h function, which is a shorthand for a Vue instance's $createElement method, must be in the scope where the JSX is. 详细
createElement
方法比较多,好比能够把columns
放在组件内部经过this.$createElement
,此处是1个简单例子dangerouslySetInnerHTML
无效,须要使用babel-plugin-transform-vue-jsx
的属性domPropsInnerHTML
以上。babel