跳到主要内容

Vue 的 slot 是什么(高级)

需要知道:基本使用,作用域插槽和具名插槽

<template>
<div>
<!--slot 基本使用-->
<SlotDemo :url="website.url">
{{website.title}}
</SlotDemo>
<hr>
<!--slot 作用域插槽-->
<ScopedSlotDemo :url="website.url">
<template v-slot="slotProps">
{{slotProps.slotData.subTitle}}
</template>
</ScopedSlotDemo>
<hr>
<!--slot 具名插槽-->
<NamedSlot>
<template v-slot:header>
<h1>插入 header slot 中</h1>
</template>
<p> 插入到 main slot中,即未命名的 slot</p>
<template v-slot:footer>
<p> 插入到 footer slot 中</p>
</template>
</NamedSlot>
</div>
</template>
<script>
import SlotDemo from './SlotDemo'
import ScopedSlotDemo from './ScopedSlotDemo'
import NamedSlot from './NamedSlot'
export default {
name: "index",
components: {
SlotDemo,
ScopedSlotDemo,
NamedSlot
},
data() {
return {
website: {
url: 'http://father.cn',
title: '父组件',
subTitle: '父组件副标题'
}
}
}
}
</script>

slot 基本使用

<template>
<a :href="url">
<slot>
默认内容,即父组件没设置内容时,显示这里
</slot>
</a>
</template>
<script>
export default {
name: "SlotDemo",
props: ['url'],
data() {
return {}
}
}
</script>

slot 作用域插槽

<template>
<a :href="url">
<slot :slotData="website">
{{website.subTitle}}<!--默认显示 subTitle,即父组件没设置内容时,显示这里-->
</slot>
</a>
</template>
<script>
export default {
name: "SlotDemo",
props: ['url'],
data() {
return {
website: {
url: 'http://child.cn',
title: '子组件',
subTitle: '子组件副标题'
}
}
}
}
</script>

slot 具名插槽

<template>
<div>
<header>
<slot name="header"></slot>
</header>
<main>
<slot></slot>
</main>
<footer>
<slot name="footer"></slot>
</footer>
</div>
</template>
<script>
export default {
name: "NamedSlot"
}
</script>