在 Vue 3 中,slot 用于讓組件的使用者可以向組件內部插入自定義內容。Vue 3 提供了多種聲明和使用插槽的方式,下面為你詳細介紹不同類型插槽的聲明方法和對應的調用方式。
1. 匿名插槽
聲明方法
在組件模板中直接使用 標簽來定義匿名插槽,它可以接收組件使用者傳入的任意內容。
<!-- MyComponent.vue -->
<template><div><h2>這是組件標題</h2><slot></slot></div>
</template>
調用方式
在使用該組件時,直接在組件標簽內寫入要插入的內容,這些內容會被插入到匿名插槽的位置。
<template><MyComponent><p>這是插入到匿名插槽的內容</p></MyComponent>
</template>
2. 具名插槽
聲明方法
在組件模板中使用 name 屬性為 標簽命名,從而定義具名插槽。
<!-- MyComponent.vue -->
<template><div><header><slot name="header"></slot></header><main><slot></slot></main><footer><slot name="footer"></slot></footer></div>
</template>
調用方式
在使用組件時,使用 標簽并通過 v-slot 指令指定要插入的具名插槽名稱。v-slot 可以簡寫為 #。
<template><MyComponent><template #header><h1>這是頭部內容</h1></template><p>這是插入到匿名插槽的內容</p><template #footer><p>這是底部內容</p></template></MyComponent>
</template>
3. 作用域插槽
聲明方法
作用域插槽允許組件向插槽內容傳遞數據。在組件模板中,通過在 標簽上綁定屬性來傳遞數據。
<!-- MyComponent.vue -->
<template><div><slot :items="items"></slot></div>
</template><script setup>
import { ref } from 'vue';
const items = ref(['蘋果', '香蕉', '橙子']);
</script>
調用方式
在使用組件時,通過 v-slot 指令接收傳遞的數據,語法為 v-slot:插槽名=“變量名”,可以使用解構賦值來獲取具體的數據。
<template><MyComponent><template #default="{ items }"><ul><li v-for="item in items" :key="item">{{ item }}</li></ul></template></MyComponent>
</template>
4. 具名作用域插槽
聲明方法
具名作用域插槽結合了具名插槽和作用域插槽的特點,在具名插槽的基礎上傳遞數據。
<!-- MyComponent.vue -->
<template><div><slot name="list" :items="items"></slot></div>
</template><script setup>
import { ref } from 'vue';
const items = ref(['蘋果', '香蕉', '橙子']);
</script>
調用方式
在使用組件時,使用 v-slot 指令指定具名插槽,并接收傳遞的數據。
<template><MyComponent><template #list="{ items }"><ul><li v-for="item in items" :key="item">{{ item }}</li></ul></template></MyComponent>
</template>
通過以上不同類型插槽的聲明和調用方式,你可以在 Vue 3 中靈活地實現組件內容的自定義插入和數據傳遞。