ivew table组件二次封装,解决slot-scope跨组件传递的问题
1. 需求
iview Table组件支持自定义列模板
<template>
<Table :columns="columns" :data="tableData">
<template slot-scope="{ row }" slot="name">
<strong>{{ row.name }}</strong>
</template>
</Table>
</template>
<script>
export default {
data () {
return {
columns: [
{
title: 'Name',
slot: 'name'
}
],
tableData: [{ name: 'John Brown' }]
}
}
}
</script>
工作中,常常会对Table组件进行二次封装,那么怎么将插槽内容从父组件中传入封装的组件中呢?
2. 解决办法
封装的组件custom-table.vue
<template>
<Table :columns="columns" :data="tableData">
<template v-for="column in columns" :slot="column.slot?column.slot:''" slot-scope="params" >
<slot :name="column.slot?column.slot:''" v-bind="params" ></slot>
</template>
</Table>
</template>
<script>
export default {
props: [columns, tableData]
}
</script>
在父组件list.vue中使用如下:
<template>
<custom-table :columns="columns" :tableData="tableData">
<template slot-scope="params" slot="operater">{{params.row.id}}</template>
</custom-table>
</template>
<script>
import CustomTable from "@/components/custom-table";
export default {
components: { CustomTable },
data() {
return {
tableData: [{id: 1}],
columns: [{
title: '操作',
slot: 'operater'
}]
}
}
}
</script>
封装后使用方式和原iview Table保持一致。