赞
踩
<template> <div> <el-table :data="data" border stripe fit style="width: 100%"> <el-table-column v-for="(value, key) in header" :key='key' //循环生成header :prop="key" :label="value" :width="columnWidths[key]" //指定某一行的具体宽度 align = "center" > <template slot-scope='scope'> //使用element-ui table 里边的scope <slot v-if='slotColumns.indexOf(key) > -1' :name = 'key v-bind='scope'> //判断slotColumns传进来的值key里边是否存在 给调用他的父级传scope <template v-else>{{{{scope.row[key]}}}}</template> //用于某一列需要特殊处理 </template> </el-table-column> <slot name="oprate"><slot> //预留一个空的插槽可以添加在父级上边调用比较多的组件方法 </el-table> </div></template><script>import ElementUI from 'element-ui';Vue.use(ElementUI); export default{ props:{ header:{ type: Object, default:()=>({}) }, data:{ type: Array, default:()=>[] }, columnWidths:{ type: Array, default:()=>[] }, slotColumns:{ type: Array, default:()=>[] } } }</script>
父组件调用
<template> <div class='tables'> <Tables :header='header' :data='data' :columnWidths='columnWidths' :slotColumns='slotColumns'> <template slot='status_name' slot-scope="scope"> //拿到slot传过来的scope <span :class = 'setStatusColor(scope.row)'>{{scope.row.status_name}} </span> </template> <template slot='create_time' slot-scope="scope"> //拿到slot传过来的scope <span>{{new Date(scope.row.create_time).getTime()}}</span> </template> <template slot='oprate'> //可以插入tables里边的固定栏如 <el-table-column fixed="right" label="人群运算" width="100" align = "center" > <template slot-scope="scope"> <el-button @click="handleClick(scope)" type="text" size="small">组合</el-button> <el-button type="text" size="small">拓展</el-button> </template> </el-table-column> </template> </Tables> </div></template> <script> import Tables from './tables' export default { components:{ Tables }, data() { return { header:{status_name:'状态', create_time: '创建时间' , crowd_name: '名称'} data:[ { create_time: "2019-06-12 10:37:37" crowd_name: "Game-拓展" status: 2 status_name: "" }, { create_time: "2019-06-12 10:37:37" crowd_name: "Game-拓展" status: 1 status_name: "构建中" } ] columnWidths: { crowd_name: 180 }, slotColumns: ['status_name', 'create_time'] //多个灵活调用插槽 } }, methods: { setStatusColor(row) { return ['is-building', 'is-builded'][row.status-1] } } }</script>