vue进阶学习之路2-slot插槽

293 阅读2分钟

Slot的通俗理解

  • 是“占坑”,在组件模板中占好了位置,当使用该组件标签时候,组件标签里面的内容就会自动填坑(替换组件模板中位置)。
  • 是对组件的扩展,通过slot插槽向组件内部指定位置传递内容,通过slot可以父子传参。

Slot的分类

  • 匿名插槽
  • 具名插槽
  • 作用域插槽

一、匿名插槽

匿名插槽,也称单个插槽。单个插槽可以放置在组件的任意位置,但是就像它的名字一样,一个组件中只能有一个该类插槽。

<div id="father">
    <h3>这里是父组件</h3>
    <child>
        <div class="tmpl">
            <span>菜单1</span>
            <span>菜单2</span>
            <span>菜单3</span>
        </div>
    </child>  
</div>  
<script>
    Vue.component('Child',{
        template: `<div>
            <h5>这里是子组件</h5>
            <slot></slot>
        </div>`,
    })
    const father = new Vue({
        el: '#father',
        data: {}
    });
</script> 

二、具名插槽

插槽加了名称属性,就变成了具名插槽。具名插槽可以在一个组件中出现Ñ次,出现在不同的位置。

<div id="father">
    <h3>这里是父组件</h3>
    <child>
        <div class="tmpl" slot="childOne">
            <span>菜单1</span>
            <span>菜单2</span>
            <span>菜单3</span>
        </div>
    </child>  
</div>  
<script>
    Vue.component('Child',{
        template: `<div>
            <h5>这里是子组件</h5>
            <slot name='childOne'></slot>
        </div>`,
    })
    const father = new Vue({
        el: '#father',
        data: {}
    });
</script> 

三、作用域插槽

作用域插槽,实际上,对比前面两种插槽,我们可以叫它带数据的插槽。

作用域插槽要求,在槽上面绑定数据
<div id="father">
    <h3>这里是父组件</h3>      
    <child>
            <template slot-scope="user">
                <ul>
                    <li v-for="(item, index) in user.data" :key="index">{{item}}</li>
                </ul>
            </template>
    </child>  
</div>  
<script>
    Vue.component('Child',{
        template: `<div>
            <h5>这里是子组件</h5>
            <slot :data="data"></slot>
        </div>`,
        data: function(){
            return {
                data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
            }
        }
    })
    const father = new Vue({
        el: '#father',
        data: {}
    });
</script>