- 插槽slot(2)
渲染作用域
插槽内容可以访问到父组件的数据作用域,因为插槽内容本身是在父组件模板中定义的
SlotsTow.vue
vue
<script>
export default {
data() {
return {};
}
}
</script>
<template>
<h3>Slots续集</h3>
<slot></slot>
</template>
App.vue
vue
<script>
import SlotsTow from "@/components/SlotsTow.vue";
export default {
components: {
SlotsTow
},
data() {
return {
message: "插槽内容续集"
}
}
}
</script>
<template>
<SlotsTow>
<h3>{{ message }}</h3>
</SlotsTow>
</template>

默认内容
在外部没有提供任何内容的情况下,可以为插槽指定默认内容
vue
<template>
<h3>Slots续集</h3>
<slot>插槽默认值</slot>
</template>

具名插槽
多个插槽情况下:
SlotsTow.vue
vue
<template>
<h3>Slots续集</h3>
<slot name="header">插槽默认值</slot>
<hr>
<slot name="main">插槽默认值</slot>
</template>
App.vue
vue
<template>
<SlotsTow>
<template v-slot:header>
<h3>{{ message }}</h3>
</template>
<template v-slot:main>
<h3>内容</h3>
</template>
</SlotsTow>
</template>
v-slot
有对应的简写#
,因此<template v-slot:header>
可以简写为<template #header>
。其意思就是"将这部分模板片段传入子组件的header
插槽中