Vue slot简单理解

情形一:

子组件定义了具名的slot,父组件使用具名的slotslot显示顺序为子组件定义slot的顺序

子组件:

Vue.component('child',{
        template:`<div class="child"><slot name="one"></slot><slot name="two"></slot></div>`
    });

父组件使用子组件:

<child>
        <h1 slot="two" class="two">woshi  two</h1>
        <h2 slot="one" class="one">woshi  one</h2>
</child>

显示顺序按照子组件slot定义的顺序。

情形二:

子组件定义了不具名的slot,父组件直接使用子组件,并可以直接在子组件中写内容

子组件:

Vue.component('btn',{
        template:`<div class="button">
    <slot></slot>
</div>`
    });

父组件:

<btn>
        按钮
</btn>

情形三:

子组件slot中定义了默认内容,如果父组件引入了子组件,且不写内容,则显示子组件默认内容,子组件定义的默认内容也可以提前加任何样式或赋予任何标签。但是slot标签上不可以加任何样式。如果父组件引入定义了slot的子组件,并且赋予了内容,则子组件默认的slot中的标签与样式不会加上去。如果想要给slot加样式,要加在父组件上。

子组件:

Vue.component('aaa',{
        template:`<div>
    <slot><h1 style="color:red">woshi slot默认内容</h1></slot>
</div>`
});

父组件:

<aaa></aaa>
<aaa><h6>哈哈哈哈哈</h6></aaa>
<aaa>哈哈哈哈哈</aaa>

 vue dom元素挂载:

new Vue({
        el:"#app"
 })
原文地址:https://www.cnblogs.com/beileixinqing/p/7508899.html