使用場景
官方解釋,有時讓插槽內容能夠訪問子組件中才有的數據是很有用的。比如我們在使用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 指令來實現。
最終顯示效果其實是一樣的。