vue中匿名插槽,具名插槽,作用域插槽的区别

面试的时候可能会问你,什么叫做内容分发  说实话这个问题很模糊 想回答的准确点确实有点难

一个通俗点的回答就是 父组件的数据和子组件的模板配合起来使用就是内容分发 

内容分发其实和一个叫做插槽的概念有关  slot关键字

这里有三种插槽 我们就来一一讲解  

1.匿名插槽  又叫做默认插槽 就是没有名字

我还是直接上代码 更直接点

1.1.在父组件中   子组件引用的中间也有内容 有代码  父组件可以决定里面html代码的样式 还有数据内容

<h2>这里是父组件</h2>

<child>

         <div>

               <h2>hello</h2>

               <h2vue.js</h2>

         </div>

</child>

1.1. 子组件   使用  slot 插槽标签  可以上父组件传来的内容进行展示 至于在哪里展示 由子组件决定

<template>

    <div>

        <h2>这里是子组件</h2>

        <slot ></slot>

    </div>

</template>

这是在页面上的显示效果

2.具名插槽   这个和匿名插槽 区别就是这个是由名字  在标签上  加一个slot 属性 起一个自定义的名字

2.1 在父组件

<h2>这里是父组件</h2>

<child>

         <div>

               <h2>hello</h2>

               <h2vue.js</h2>

              <h2 slot="react"  style="color:#f00">react.js</h2>      //我们还给他改变了颜色

         </div>

</child>

2.2. 在子组件中    引用的时候 我们 需要在 slot标签上加上 一个  name属性 名字 就是我们在父组件中自定义的那个名字

<template>

    <div>

        <h2>这里是子组件</h2>

        <slot ></slot>   //  没有名字的都会被收到这个匿名插槽中间

      <slot name="react"></slot>

    </div>

</template>

最后也确实 显示  这就是 具名插槽的作用  注意 没有其名字的插槽 都会被 匿名插槽所接收  

3.作用域插槽  这下和具名插槽有俩点不同   功能快和具名插槽作用相反了

3.1 是父组件引用子组件中的数据 

3.2 使用slot-scope 进行数据的传递

子组件中 将数据传递给父组件

<template>

    <div>

        <h2>这里是子组件</h2>

         <slot :data="data"></slot>    // 有点和 props  传递参数有点像是吧

    </div>

</template>

data(){

            return {

                data:['tom','jack','rose','tony','stark']

            }

}

在父组件中

<child>

         <template slot-scope="user">   // 这里自定义一个变量 我们传的数据会到这个对象下面 使用的时候是  user.data                                                                             // data就是好我们传过来的数据

                <div class="tmp">

                    <span v-for="item in user.data" :key="item">{{item}}</span>

                </div>

            </template>

</child>

同时我们在给设置一个弹性布局

.tmp{

        display: flex;

        justify-content: space-around;

    }

最后页面显示效果如下

<child>    // 如果我们不用 slot-scope进行接受的话 子组件的作用域插槽 就会变成了 普通的 匿名插槽了

          hello world

</child> 

好了 到此结束了  

发布了141 篇原创文章 · 获赞 64 · 访问量 9137

猜你喜欢

转载自blog.csdn.net/yunchong_zhao/article/details/104253635