1. 程式人生 > >vue中的插槽slot

vue中的插槽slot

spa 綁定 第四次 htm span 不同 有一個 item lex

插槽(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‘]
}
}
}

vue中的插槽slot