vue2插槽

插槽的使用其實(shí)是很簡單,你只需要明白兩點(diǎn):

1.插槽是使用在子組件中的。
2.插槽是為了將父組件中的子組件模板數(shù)據(jù)正常顯示

話不多說直接上案例:

<div id="app">
    <div class="father">
        <h3>這里是父組件</h3>
        <child>
           <span>我是插槽插入的內(nèi)容</span>
        </child>
    </div>
</div>
<template id="child">
    <div class="child">
        <h3>這里是子組件</h3>
        <slot></slot>
    </div>
</template>
<script>
    var app= new Vue({
        el: '#app',
        data: {},
        components: {
            child: {
                template: '#child'
            }
        }
    });

</script>

上面的代碼所展示的效果就是你會(huì)發(fā)現(xiàn)在 <h3>這里是子組件</h3> 會(huì)多一行 <span>我是插槽插入的內(nèi)容</span>
如果你在子組件里面不寫<slot></slot>的話你會(huì)發(fā)現(xiàn)你無論在父組件里面寫多少標(biāo)簽都不會(huì)被渲染到子標(biāo)簽中。

上面的案例是匿名插槽,下面我們來看一下 “具名插槽”

<div id="app">
    <div class="father">
        <h3>這里是父組件</h3>
        <child>
            <span slot="demo1">菜單1</span>
            <span>菜單2</span>
            <span slot="demo3">菜單3</span>
        </child>
    </div>
</div>
<template id="child">
    <div class="child">
        <h3>這里是子組件</h3>
        <slot></slot>
        <slot name="demo3"><slot>
    </div>
</template>
<script>
    var app= new Vue({
        el: '#app',
        data: {},
        components: {
            child: {
                template: '#child'
            }
        }
    });
</script>

具名插槽其實(shí)就是在父組件中添加一個(gè) slot='自定義名字' 的屬性,然后在子組件中的<slot><slot> 里面添加 <name='自定義名字' 即可如果父組件中有一部分沒有添加 slot 屬性,則此處就是默認(rèn)的插槽,在子組件中的<slot></slot> 直接就是使用的父組件的默認(rèn)插槽部分。

作用域插槽

父組件模板的所有東西都會(huì)在父級作用域內(nèi)編譯;子組件模板的所有東西都會(huì)在子級作用域內(nèi)編譯。不過,我們可以在父組件中使用slot-scope 特性從子組件獲取數(shù)據(jù),前提是需要在子組件中使用:data=data 先傳遞data 的數(shù)據(jù)。

<div id="app">
    <div class="father">
        <h3>這里是父組件</h3>
        <child>
            <div slot-scope="user">
                {{user.data}}
            </div>
        </child>
    </div>
</div>
<script>
    Vue.component('child', {
        template:'' +
            '<div class="child">\n' +
            '    <h3>這里是子組件</h3>\n' +
            '    <slot  :data="data"></slot>\n' +
            '  </div>',
        data: function () {
            return {
                data: ['zhangsan', 'lisi', 'wanwu', 'zhaoliu', 'tianqi', 'xiaoba']
            }
        }
    });
    var vm = new Vue({
        el: '#app',
    });
</script>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容