深入探索slot

82 阅读1分钟

插槽:

插槽: 在一个组件中,引用的子组件里面按道理来说是不能写标签的,如果想在里面写标签的,可以使用插槽(slot)的方式,可以在子组件中加入插槽,就可以在父组件的子组件里面写想要的标签了。(这个标签其实相当于写子组件在插槽里面的,父组件引用这个子组件从而使用了里面的标签)

  1. 匿名插槽 官方叫做:单个插槽,顾名思义,一个组件里面只能有一个该类别的插槽
父组件
<template>
    <div class="father">
        <h3>这里是父组件</h3>
        <child>
            <div class="tmpl">
              <span>菜单1</span>
              <span>菜单2</span>
              <span>菜单3</span>
              <span>菜单4</span>
              <span>菜单5</span>
              <span>菜单6</span>
            </div>
        </child>
    </div>
</template>



子组件
<template>
    <div class="child">
        <h3>这里是子组件</h3>
        <slot></slot>   //插槽
    </div>
  1. 具名插槽 命名了具体的名字,在父组件中通过使用名字来找到相应的插槽,一个组件里面可以有多个该类别的插槽但是前提是需要名字不同
父组件
<template>
  <div class="father">
    <h3>这里是父组件</h3>
    <child>
      <div class="tmpl" slot="up">
        <span>菜单1</span>
        <span>菜单2</span>
        <span>菜单3</span>
        <span>菜单4</span>
        <span>菜单5</span>
        <span>菜单6</span>
      </div>
      <div class="tmpl" slot="down">
        <span>菜单-1</span>
        <span>菜单-2</span>
        <span>菜单-3</span>
        <span>菜单-4</span>
        <span>菜单-5</span>
        <span>菜单-6</span>
      </div>
      <div class="tmpl">
        <span>菜单->1</span>
        <span>菜单->2</span>
        <span>菜单->3</span>
        <span>菜单->4</span>
        <span>菜单->5</span>
        <span>菜单->6</span>
      </div>
    </child>
  </div>
</template>




子组件
<template>
  <div class="child">
    // 具名插槽
    <slot name="up"></slot>
    <h3>这里是子组件</h3>
    // 具名插槽
    <slot name="down"></slot>
    // 匿名插槽
    <slot></slot>
  </div>
</template>
  1. 作用域插槽 也叫做带数据的插槽,匿名插槽和具名插槽都是在组件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上绑定数据
    <slot  :data="data"></slot>
  </div>
</template>

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

引用 SentMes