網(wǎng)站公司哪家好哪家網(wǎng)站推廣好
文章目錄
- 插槽(Slots)
- 無名插槽(默認插槽)
- 具名插槽
- `reference` 插槽
- 使用 `v-slot` 的縮寫語法
插槽(Slots)
在 Vue
中,插槽(Slots
)是一種組件內(nèi)容分發(fā)的機制,允許你將內(nèi)容從父組件傳遞到子組件的模板中。插槽可以有名字,這樣你就可以在子組件中定義多個插槽,并且在父組件中指定哪些內(nèi)容應(yīng)該放入哪個插槽。
以下是一些常見的插槽用法,包括 header
、footer
和 reference
插槽:
無名插槽(默認插槽)
無名插槽是最簡單的插槽類型,如果沒有指定插槽的名字,那么它就是默認插槽。
子組件:
<template><div><slot></slot> <!-- 默認插槽內(nèi)容將在這里渲染 --></div>
</template>
父組件:
<template><ChildComponent><p>這是一些默認插槽內(nèi)容。</p></ChildComponent>
</template><script>
import ChildComponent from './ChildComponent.vue';
</script>
具名插槽
具名插槽允許你在一個組件中有多個內(nèi)容插入點。
子組件:
<template><div><slot name="header"></slot> <!-- header 插槽內(nèi)容將在這里渲染 --><slot name="default"></slot> <!-- 默認插槽內(nèi)容將在這里渲染 --><slot name="footer"></slot> <!-- footer 插槽內(nèi)容將在這里渲染 --></div>
</template>
父組件:
<template><ChildComponent><template v-slot:header><h1>這是頭部內(nèi)容</h1></template><p>這是默認插槽內(nèi)容。</p><template v-slot:footer><p>這是底部內(nèi)容</p></template></ChildComponent>
</template><script>
import ChildComponent from './ChildComponent.vue';
</script>
reference
插槽
reference
插槽通常用于定義一個觸發(fā)元素,例如在彈出組件中。
子組件:
<template><div><slot name="reference"></slot> <!-- 觸發(fā)元素將在這里渲染 --><div>彈出內(nèi)容...</div></div>
</template>
父組件:
<template><ChildComponent><template v-slot:reference><button>點擊我</button></template></ChildComponent>
</template><script>
import ChildComponent from './ChildComponent.vue';
</script>
在這個例子中,<button>
元素是觸發(fā)彈出的參考元素,當用戶點擊按鈕時,子組件會顯示彈出內(nèi)容。
使用 v-slot
的縮寫語法
在 Vue 2.6.0+
和 Vue 3
中,你可以使用 v-slot
的縮寫語法 #
:
父組件(使用縮寫語法):
<template><ChildComponent><template #header><h1>這是頭部內(nèi)容</h1></template><p>這是默認插槽內(nèi)容。</p><template #footer><p>這是底部內(nèi)容</p></template></ChildComponent>
</template>
這種縮寫語法使得模板更加簡潔易讀。記住,無論是使用完整的 v-slot
語法還是縮寫語法,插槽的用法都是相同的。