Vue - 插槽(slot)

插槽,也就是slot,是组件的一块HTML模板,这块模板显示不现实、以及怎样显示由父组件来决定。

插槽模板是slot,它是一个空壳子,因为它显示与隐藏以及最后用什么样的html模板显示由父组件控制。但是插槽显示的位置由子组件自身决定,slot写在组件template的哪块,父组件传过来的模板将来就显示在哪块。这样就使组件可复用性更高,更加灵活。我们可以随时通过父组件给子组件加一些需要的东西。

一、插槽内容

插槽内可以是任意内容。首先声明一个child-component组件,给组件增加一个<slot></slot>插槽。
现在我想在<child-component></child-component>内放置一些内容

<div id="app">
    <child-component>你好</child-component>

</div>
<script>
  Vue.component('child-component',{
        template:`
            <div>
            Hello,World!
            <slot></slot>
            </div>
        `
    })
    let vm = new Vue({
        el:'#app',
        data:{

        }
    })
</script>
 

二、具名插槽

具名插槽,就是给这个插槽起一个名字
在组件中,我给插槽起个名字,一个名字叫"a",一个名字叫"b",还有一个不起名字。
然后再<child-component></child-component>内,slot属性对应的内容都会和组件中name一一对应。
而没有名字的,就是默认插槽!!

<div id="app">
    <child-component>
        <template slot="a">
            漂亮
        </template>
        <template slot="b">
            帅气
        </template>
        <div>
            我是默认的插槽
        </div>
    </child-component>
</div>
<script>
    Vue.component('child-component',{
        template:`
            <div>
            <h4>a和b</h4>

            <slot name="a"></slot>

            <div style="height:1px;"></div>

            <slot name="b"></slot>

            <div style="height:1px;"></div>

            <slot></slot>
            </div>
        `
    })
    let vm = new Vue({
        el:'#app',
        data:{

        }
    })
</script>

三、作用域插槽

在组件上的属性,可以在组件元素内使用!

<child :lists="nameList">
<template slot-scope="a">
{{a}}
</template>
</child>

<li v-for="list in lists">
<slot :bbbbb="list"></slot>
</li>
 

猜你喜欢

转载自www.cnblogs.com/gitnull/p/10085015.html