插槽的概念
插槽就是子組件中的提供給父組件使用的一個占位符,用slot標簽 表示,父組件可以在這個占位符中填充任何模板代碼,如 HTML、組件等,填充的內容會替換子組件的slot標簽。簡單理解就是子組件中留下個“坑”,父組件可以使用指定內容來補“坑”。
默認插槽
<!-- 子組件 ChildComponent.vue -->
<template><div><h2>子組件標題</h2><slot>這是默認內容,當父組件不提供內容時顯示</slot></div>
</template><!-- 父組件使用 -->
<child-component><p>這是父組件插入的內容</p>
</child-component>
具名插槽
》》當需要多個插槽時,可以使用具名插槽:
<!-- 子組件 Layout.vue -->
<template><div><header><slot name="header"></slot></header><main><slot></slot> <!-- 默認插槽 --></main><footer><slot name="footer"></slot></footer></div>
</template><!-- 父組件使用 -->
<layout><template slot="header"><h1>頁面標題</h1></template><p>主要內容區域</p> <!-- 默認插槽內容 --><template v-slot:footer><p>頁腳信息</p></template>
</layout>
作用域插槽
作用域插槽的使用情景:當數據在組件(子)自身,但根據數據生成的結構需要組件(父)使用者來定,我們則可以使用作用域插槽
<!-- 子組件 ScopedComponent.vue -->
<template><div><slot :user="user" :age="age"></slot></div>
</template><script>
export default {data() {return {user: '張三',age: 25}}
}
</script><!-- 父組件使用 -->
<scoped-component><template v-slot:default="slotProps"><p>用戶名: {{ slotProps.user }}</p><p>年齡: {{ slotProps.age }}</p></template>
</scoped-component>