vue 開發系列(十) VUE 作用域插槽


使用場景

官方解釋,有時讓插槽內容能夠訪問子組件中才有的數據是很有用的。比如我們在使用ant-design-vue 的表格控件時。

 <a-table-column title="注釋" dataIndex="comment"  >
                   <template slot-scope="text, record">
                     <rx-textbox v-model="record.comment" ></rx-textbox>
                    </template>
                 </a-table-column>

這里從控件傳遞數據到父組件,我們在使用組件的時候,可以根據我們的需要顯示需要的效果,表格控件並不需要關心如何實現數據的展示。

我們怎么理解這個作用域插槽呢?

下面我們舉一個簡單的例子還說明這個問題。

 

實現過程

編寫子組件

<template>
 <div class="child">
    <h3>這里是子組件</h3>
    <slot name="demo" :text="account" :record="user"></slot>
  </div>
</template>

<script>
export default {
    name:"child",
    data(){
      return {
        user: ['張三','李四',"王五"],
        account:"ray"
      }
    }
}
</script>

這里有兩個知識點。

1.具名插槽

2.傳遞數據

把帳號和記錄數據傳遞出去。

父組件代碼

<template>
  <div class="father">
    <child>
      <template  slot="demo" slot-scope="{text,record}">
       {{text}}
       <div v-for="item in record" :key="item">{{item}}</div>
      </template>
    </child>
     <child>
      <template  v-slot:demo="{text,record}">
       {{text}}
       <div v-for="item in record" :key="item">{{item}}</div>
      </template>
    </child>
  </div>
</template>

<script>
import Vue from 'vue'

import ChildSlot from '@/components/ChildSlot.vue'

Vue.component(ChildSlot.name, ChildSlot);

export default {
  name: 'HelloWorld',
 
}
</script>

在這里例子中我展示了兩種寫法:

slot="demo" slot-scope="{text,record}"

這種寫法 其實不推薦使用的,這個在2.6之后是需要廢棄的。

<template  v-slot:demo="{text,record}">

推薦寫法使用 v-slot 指令來實現。

 

 最終顯示效果其實是一樣的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM