插槽-slot
- 基本使用
- 作用域插槽
- 具名插槽
1. 基本使用
比较简单, 比如:
<template>
<a :href=”url”>
<slot :slotData=”website”>xxxx</slot>
</a>
</template>
父页面使用--不用获取slotdemo组件里面的数据的时候:
<slotDemo :url="xxx”>
xxxxx
</slotDemo>
2. 作用域插槽
1) scope 只可以用于 <template> 元素,其它和 slot-scope 都相同(已被移除)。
2) slot-scope 用于将元素或组件表示为作用域插槽,可以接收传递给插槽的 prop 。(在 2.5.0+ 中替代了 scope,自 2.6.0 起被废弃)
3) 推荐使用v-slot,默认插槽只传递参数v-slot="xxx"
3. 具名插槽
1) 用于 <template> 元素, v-slot:名字="xxx"
2) 或者#名字
使用示例:
子页面:
<template>
<div>
<header>
<slot name="header">具名插槽-header</slot>
</header>
<main>
<slot :slotData="slotData">
作用域插槽 :slotData="slotData"方便父页面获取插槽数据
</slot>
</main>
<footer>
<slot name="footer">具名插槽-footer</slot>
</footer>
</div>
</template>
<script>
export default {
data () {
return {
slotData: {
title: 'title-aaa'
}
}
}
}
</script>
父页面:
<template>
<div class="a-box">
<NameSlot>
<!-- 具名插槽 -->
<template v-slot:header>
<div>头部---</div>
</template>
<!-- 作用域插槽: 方便获取插槽的数据 -->
<template v-slot="slotProps">
<div>{{ slotProps.slotData.title }}</div>
</template>
<!-- 具名插槽 -->
<template #footer>
<div>底部----</div>
</template>
</NameSlot>
</div>
</template>
<script>
import NameSlot from './Slot1'
export default {
components: {
NameSlot
}
}
</script>
<style lang="css" scoped>
.a-box {
width: 300px;
height: 300px;
background-color: red;
font-size: 33px;
}
</style>