1. 程式人生 > 程式設計 >vue插槽slot的簡單理解與用法例項分析

vue插槽slot的簡單理解與用法例項分析

本文例項講述了vue插槽slot的簡單理解與用法。分享給大家供大家參考,具體如下:

vue中插槽的使用非常廣泛,本文就插槽的使用和理解簡單總結。

從字面理解插槽是預先插入一個程式碼空間,用於後期塞入資料。

插槽分類

匿名插槽 ------------------匿名的程式碼空間

具名插槽 ------------------帶有命名的程式碼空間

作用域插槽 -------------------帶有資料的程式碼空間

插槽使用示例

匿名插槽

說明在元件中先定義預留的程式碼空間,元件在使用時直接寫入程式碼

<template>
 <div class="child">
  <h3>這裡是子元件</h3>
  <slot></slot>
 </div>
</template>

使用:

<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>

具名插槽

預先在元件中定義一個帶有名稱的程式碼空間,使用元件時用:slot繫結名稱

<template>
 <div class="child">
 // 具名插槽
 <slot name="up"></slot>
 <h3>這裡是子元件</h3>
 // 具名插槽
 <slot name="down"></slot>
 // 匿名插槽
 <slot></slot>
 </div>
</template>

使用:

<template>
 <div class="father">
 <h3>這裡是父元件</h3>
 <child>
  //插槽up
  <div class="tmpl" slot="up">
  <span>選單1</span>
  <span>選單2</span>
  <span>選單3</span>
  <span>選單4</span>
  <span>選單5</span>
  <span>選單6</span>
  </div>
  //插槽down
  <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">
 
 <h3>這裡是子元件</h3>
 // 作用域插槽
 <slot :data="data"></slot>
 </div>
</template>
 export default {
 data: function(){
  return {
  data: ['zhangsan','lisi','wanwu','zhaoliu','tianqi','xiaoba']
  }
 }
}

使用

<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>

總結:

匿名插槽和具名插槽的功能是 預留插入程式碼的空間

作用域插槽是提供資料資源,預留程式碼渲染邏輯空間

希望本文所述對大家vue.js程式設計有所幫助。