Vue3 學(xué)習(xí)筆記—插槽使用大全
在 2.6.0中,vue 為具名插槽和作用于插槽引入了一個(gè)新的統(tǒng)一語法:v-slot。它取代了 slot 和 slot-scope 在新版中的應(yīng)用。
本篇文章主要介紹在 vue3 中插槽的使用。
一、v-slot 介紹
v-slot 只能用在 template 或組件上使用,否則就會報(bào)錯(cuò)。
v-slot 也是其中一種指令。
使用示例:
- //父組件代碼
 - <child-com>
 - <template v-slot:nameSlot>
 - 插槽內(nèi)容
 - </template>
 - </child-com>
 - //組件模板
 - <slot name="nameSlot"></slot>
 
v-slot 的語法,簡化 slot、slot-scope 作用域插槽的功能,相比更加強(qiáng)大,代碼效率更高。
二、匿名插槽
當(dāng)組件中只有一個(gè)插槽的時(shí)候,可以不設(shè)置 slot 的 name 屬性,v-slot 后可以不帶參數(shù),但是 v-slot 在沒有設(shè)置 name 屬性的插槽口也會帶有隱含的 “default”。
匿名插槽使用:
- //組件調(diào)用
 - <child-com>
 - <template v-slot>
 - 插槽內(nèi)容
 - </template>
 - </child-com>
 - //組件模板
 - <slot ></slot>
 
雖然 v-slot 沒有設(shè)置參數(shù),但不能刪除掉 ,否則插槽內(nèi)容無法正常渲染。
三、具名插槽
一個(gè)組件中有多個(gè)插槽的時(shí)候,如果沒有設(shè)置 v-slot 屬性值,會默認(rèn)把元素插到?jīng)]有設(shè)置 name 屬性值的 slot 組件中,為了把對應(yīng)的元素放到指定的位置,就需要借助 v-slot 和 name 屬性,把內(nèi)容對應(yīng)起來。
具名插槽使用:
- //父組件
 - <child-com>
 - <template v-slot:header>
 - 頭部
 - </template>
 - <template v-slot:body>
 - 內(nèi)容
 - </template>
 - <template v-slot:footer>
 - 腳
 - </template>
 - </child-com>
 - //子組件
 - <div>
 - <slot name="header"></slot>
 - <slot name="body"></slot>
 - <slot name="footer"></slot>
 - </div>
 
具名插槽縮寫
v-slot 與 v-bind、v-on 指令一樣,也存在縮寫。可以把 v-slot: 簡寫為 # 號。
如上述 v-slot:footer 可以簡寫為 #footer 。
上述的父組件代碼可以簡化為:
- <child-com>
 - <template #header>
 - 頭部
 - </template>
 - <template #body>
 - 內(nèi)容
 - </template>
 - <template #footer>
 - 腳
 - </template>
 - </child-com>
 
注意:和其他指令一樣,只有存在參數(shù)時(shí),才可以簡寫,否則是無效的。
四、作用域插槽
有時(shí)讓插槽內(nèi)容能夠訪問子組件中才有的數(shù)據(jù)是很有用的。當(dāng)一個(gè)組件被用來渲染一個(gè)項(xiàng)目數(shù)組時(shí),這是一個(gè)常見的情況,我們希望能夠自定義每個(gè)項(xiàng)目的渲染方式。
要使子組件上的屬性在插槽內(nèi)容上可用,需要給 slot 綁定一個(gè)屬性。然后在 v-slot 處接收并定義提供插槽 props 名字。
使用示例:
- //
 - <child-com>
 - <template v-slot:header="slotProps">
 - 插槽內(nèi)容--{{ slotProps.item }} 序號--{{ slotProps.index }}
 - </template>
 - </child-com>
 - //子組件代碼
 - <template>
 - <div v-for="(item, index) in arr" :key="index">
 - <slot :item="item" name="header" :index="index"></slot>
 - </div>
 - </template>
 - <script setup>
 - const arr = ['1111', '2222', '3333']
 - </script>
 
五、動(dòng)態(tài)插槽名
v-slot 指令參數(shù)也可以是動(dòng)態(tài)的,用來定義動(dòng)態(tài)插槽名。
如:
- <child-com>
 - <template v-slot:[dd()]>
 - 動(dòng)態(tài)插槽名
 - </template>
 - </child-com>
 - <script setup>
 - const dd = () => {
 - return 'hre'
 - }
 
此處使用的是函數(shù),也可以直接使用變量。















 
 
 









 
 
 
 