Vue的slot

这个slot的意思就是插槽,具体的用法就是当有些信息或者有些节点需要由父节点来决定时,用到。相当于,父亲的一些基因,传递了给孩子。看看例子

先看看这种情况,在以下的情况下,在父节点中,写的任何内容,都不会被展示,因为整个子节点会直接替换了父节点中定义的子节点接口。意思就是说,在父节点中<child></child>里的内容会全部抹掉,完全被child组件中的<div>I am children</div>替换掉

father.vue

<template>
    <div>
        <child>father say hi to you</child>
    </div>
</template>

<script>
    import child from './child.vue'

    export default{
        data(){
            return {
                
            }
        },
        components:{
            child,
        }
    }
</script>

child.vue

<template>
    <div>
        I am children
    </div>


</template>

<script>

    export default{
        data(){
            return {
                
            }
        },
       
    }
</script>

渲染后的结果为

<div>
    <div>I am children</div>
</div>

在这种情况,如果你想把父组件中的内容带到子子组件中,怎么办呢?就需要用到slot了,他分为两种形式,一种是单插槽,一种的多插槽,先看看单插槽

单插槽

 先在子组件中定义一个插槽,然后在父组件(father.vue代码不需要作任何修改)中写的任何内容全部都会塞到这个slot节点当中,如下面代码,和最终渲染结果

child.vue

<template>
    <div>
     <!--在这里定义了一个插槽--> <slot></slot> I am children </div> </template> <script> export default{ data(){ return { } }, } </script>

最终渲染结果

<div>
  father say hi to you
  <div>I am children</div> 

</div>

多插槽

在某种情况,不单单只插一个内容,如果需要插入多个,就需要用到以下的写法

child.vue

<template>
    <div>
     <!--在这里定义了多个插槽-->
        <slot name="slot_1"></slot>
        <slot name="slot_2"></slot>
        I am children
    </div>


</template>

<script>

    export default{
        data(){
            return {
                
            }
        },
       
    }
</script>     

father.vue

<template>
    <div>
        <child>
            <template slot="slot_1">Slot_1 is here</template>
            
            father say hi to you

            <template slot="slot_2">
                Slot_2 is here
                <div>Slot_2 DIV </div>
            </template>
        </child>
    </div>
</template>

<script>
    import child from './child.vue'

    export default{
        data(){
            return {
                
            }
        },
        components:{
            child,
        }
    }
</script>

最终渲染结果:

<div>
    <div>
        Slot_1 is here
        Slot_2 is here
        <div>Slot_2 DIV </div>
        
     I am children
</div> </div>
原文地址:https://www.cnblogs.com/oscar1987121/p/9645213.html