Vue中的slot、slot-scope和v-slot

一.slot

插槽,也就是slot,是组件的一块HTML模板,这块模板显示不显示、以及怎样显示由父组件来决定。值得注意的是:内容要写在父组件中,然后分给需要的子组件,当slot多个时,可以通过name来加以区分,这就是所谓的具名插槽。

举个例子

父组件:


<template>
    <div>
        <h3>这是父组件</h3>
        <son><span>实践slot</span></son>
        <son>
            <template slot="myslot">
                <div>
                    实践具名slot
                </div>
            </template>
        </son>
    </div>
</template>

子组件:


<template>
    <div>
        <h4>这是子组件</h4>
        <input type="text" placeholder="请输入">
        <slot></slot>
        <slot name="myslot"></slot>
    </div>
</template>

效果:
在这里插入图片描述

二.slot-scope

slot-scope就是作用域插槽。官方叫它作用域插槽,实际上,对比具名插槽,我们可以叫它带数据的插槽。具名插槽在组件的template里面写,作用域插槽要求,在slot上面绑定数据。

举个例子

父组件:

<template>
  <div class="father">
    <h3>这里是父组件</h3>
    <!--第一次使用:用flex展示数据-->
    <child>
      <template slot-scope="user">
        <div class="tmpl">
          <span v-for="item in user.data">{{item}}</span>
        </div>
      </template>

    </child>

    <!--第二次使用:用列表展示数据-->
    <child>
      <template slot-scope="user">
        <ul>
          <li v-for="item in user.data">{{item}}</li>
        </ul>
      </template>

    </child>

    <!--第三次使用:直接显示数据-->
    <child>
      <template slot-scope="user">
       {{user.data}}
      </template>

    </child>

    <!--第四次使用:不使用其提供的数据, 作用域插槽退变成匿名插槽-->
    <child>
      我就是模板
    </child>
  </div>
</template>

子组件:

<template>
  <div class="child">

    <h3>这里是子组件</h3>
    // 作用域插槽
    <slot  :data="data"></slot>
  </div>
</template>

 export default {
    data: function(){
      return {
        data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
      }
    }
}

效果:
在这里插入图片描述

三.v-slot

从 vue2.6 开始,Vue 为具名插槽和作用域插槽引入了一个全新的语法,即v-slot 指令。目的就是想统一 slot 和 scope-slot 语法,使代码更加规范和清晰。
具体使用如下:
1.插槽的名字现在通过 v-slot:slotName 这种形式来使用,如下。

<template v-slot:header> </template>

2.此处需要注意的是, v-slot 只能添加到 上,这点Vue 2.5中的slot是不同的.

<template v-slot:slotName="data"> </template>

3.正常情况下,假设Test组件注册及组件模板如下,

//组件模板
 <template id="test">
        <div>
            <h3>这里是test组件</h3>
            <slot></slot>
        </div>
    </template>
//组件注册
   Vue.component('Test', {
        template: '#test',
        data() {
            return {
                msg: 'Hello World!'
            }
        }
    })

当我们需要在下面的p标签内获取Test组件数据时,可能往往写法如下

 <Test>
            <template v-slot:default>
            <p>{{msg}}</p>
            </template>
</Test>

但是,由于组件的数据只能限于当前组件模板才能使用,所以它访问不了Test组件中的数据,为了解决这个问题,需要给组件模板中的元素上动态绑定一个对象属性,绑定到 元素上的属性我们称之为 slot props。该对象属性的名字可以自定义,而属性值就是Test组件数据的名字,这样就可以获取到Test组件中的数据,如下

   <slot :msg="msg"></slot>

同时使用v-slot重构上面代码。

  <Test>
            <template v-slot:default="data">//此处的data就是在<slot>中绑定的属性slot props
                <p>{{data.msg}}</p>
            </template>
</Test>
发布了32 篇原创文章 · 获赞 78 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/liuyifeng0000/article/details/104399602