Vue基础-匿名插槽与作用域插槽的合并和覆盖行为

Vue 测试版本:Vue.js v2.5.13

Vue 文档:

<slot> 元素可以用一个特殊的特性 name 来进一步配置如何分发内容。多个插槽可以有不同的名字。具名插槽将匹配内容片段中有对应 slot 特性的元素。

仍然可以有一个匿名插槽,它是默认插槽,作为找不到匹配的内容片段的备用插槽。

具体应用的时候:

1、匿名插槽的合并行为:

    <div id="app">
       <myele>
           <div>
               default slot
           </div>
           
           <div>
               <div>from parent!</div>
               <div>from parent!</div>
           </div>
       
       </myele>
    </div>
window.onload = function() {
    Vue.component('myele', {
        template: `                  
         <div>
          <slot></slot>
         </div>
        `
    });  

    new Vue({
        el: '#app'
    });
};

效果:内容合并

image

2、匿名作用域插槽的覆盖行为:

    <div id="app">
       <myele>
           <div slot-scope="props">
               <div>from parent!</div>
               <div>from {{props.text}}</div>
           </div>
            <div slot-scope="prop">
               <div>from </div>
               <div>{{prop.text}}</div>
           </div>       
       </myele>
    </div>
window.onload = function() {
    Vue.component('myele', {
        template: `                  
         <div>          
          <slot text="child"></slot>
          <slot text="child2"></slot>
//即使 text 和上一行一样,也不会报错,开发环境
         </div>
        `
    });  

    new Vue({
        el: '#app'
    });
};

效果:以靠后的作用域插槽模板为准,绘制了两遍;

image

3、匿名插槽模板和作用域插槽模板混合:

    <div id="app">
       <myele>
           <div>
               default slot
           </div>           
           <div slot-scope="props">
               <div>from parent!</div>
               <div>from {{props.text}}</div>
           </div>
       </myele>
    </div>
window.onload = function() {
    Vue.component('myele', {
        template: `                  
         <div>          
          <slot></slot>
          <slot text="child"></slot>
         </div>
        `
    });  

    new Vue({
        el: '#app'
    });
};

效果:匿名插槽以匿名作用域插槽模板为准进行渲染,即使你把匿名插槽模板放后面,也是一样的结果;

image

由此可以看出,最好不要使用匿名、默认插槽,最好使用具名插槽,可以减少不确定性;

参考文档:

https://cn.vuejs.org/v2/guide/components.html#具名插槽

原文地址:https://www.cnblogs.com/xianshenglu/p/8479915.html