vue中的插槽slot

插槽(slot):是组件的一块HTML模板,父组件决定这块模板显不显示以及怎么显示。

位置由子组件自身决定(slot现在组件template的什么位置,父组件传过来的模板将来就显示在什么位置)

匿名插槽:只能有一个,可以放在组件的任何位置

    <div class="father">
          //在父组件在里面写了html模块
          <son>
             //子组件的匿名插槽被下面的div模板使用了
                <div>

                    <span>菜单1</span>

                </div>

           </son>

    </div>

   <template>

        <div class="son">

            <slot></slot>

         </div>

   </template>

具名插槽:有name属性 可以在一个组件中多次出现,出现在不同的位置。

父组件:
<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>
//没有slot属性的html模板默认关联匿名插槽 <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>

 作用域插槽(带数据插槽):在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']
              }
     }
}

猜你喜欢

转载自www.cnblogs.com/pengc/p/9389874.html