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保持一致。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM