基本使用
父組件在引用的子組件中添加內容
<slotDemo :url="website.url">
{{website.title}} //父組件添加的內容
</slotDemo>
data() {
return {
website:{
url:'http://www.baidu.com',
title:'百度',
},
};
},
子組件 slotDemo.vue
<template>
<div>
<a :href="url">
<slot>
默認內容,即父組沒設置內容是,這是顯示
</slot>
</a>
</div>
</template>
作用域插槽
父組件可以拿到子組件的數據
- 1.把組件的的數據website 綁定到 slot 的一個自定義屬性slotDate上
- 2.在父組件裏定義 template 設置v-slot爲任意命名參數slotProps,
- 3.數據取值爲:slotProps.子組件命名數據.具體數據字段
子組件 ScopedSlotDemo.vue
<template>
<div>
<a :href="url">
//把組件的的數據website 綁定到 slot 的一個自定義屬性slotDate上
<slot :slotDate="website">
{{website.title}}
</slot>
</a>
</div>
</template>
<script>
export default {
props: ['url'],
data() {
return {
website:{
url:'http://www.baidu.com',
title:'百度1',
subTitle:'百度一下,你就知道1'
}
};
},
};
</script>
父組件 調用數據
<ScopedSlotDemo :url="website.url">
//在 template 設置v-slot爲任意命名參數slotProps,
// 取值 slotProps.子組件slot上自定義屬性slotDate.子組件數據
<template v-slot="slotProps">
{{slotProps.slotDate.title}}
</template>
</ScopedSlotDemo>
具名插槽
子組件 NameSlot 定義多個solt添加 name屬性來標識
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<solt></solt>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
父組件:通過v-slot:name 來匹配到相同name的子組件
<NameSlot>
<template v-slot:header>
<h1>將插入 header slot中</h1>
</template>
<p>將插入 main slot中,及未命名的slot</p>
<template v-slot:footer>
<h1>將插入 footer slot中</h1>
</template>
</NameSlot>