vue中的插槽slot

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

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

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

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

                    <span>菜单1</span>

                </div>

           </son>

    </div>

   <template>

        <div class="son">

            <slot></slot>

         </div>

   </template>

具名插槽:有name属性 能够在一个组件中屡次出现,出如今不一样的位置。code

父组件:
<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上面绑定数据(匿名插槽和具名插槽的的样式和内容都由父组件提供的模板决定)xml

父组件:
<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">htm

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

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

相关文章
相关标签/搜索