用于向子组件传递结构
1.默认插槽
//父组件中
<zizujian>
要传递的内容
</zizujian>
//子组件中
<slot />
2.具名插槽
//父组件中
<zizujian>
<template v-slot:header>
<h1>我是header</h1>
</template>
<template v-slot:footer>
<h1>我是footer</h1>
</template>
<div></div>
</zizujian>
//子组件中
<slot name="header"/>
<slot name="footer"/>
<slot />
在子组件标签中,任何没有v-slot的内容都被认为是默认插槽的内容
3.作用域插槽
用于父组件访问子组件的数据
//子组件中
<template>
<div>
<slot v-bind:childData="childUser"></slot>
</div>
</template>
<script>
export default {
data() {
return {
childUser: { Name:"Tom", Age:23 }
}
}
</script>
//父组件中
<zizujian>
<template v-slot:default="slotProps">
{{ slotProps.childData.Name}}
{{ slotProps.childData.Age}}
</template>
</zizujian>
如果被提供的内容只有默认插槽,可以直接写在子组件标签上
//父组件中
<zizujian v-slot:default="slotProps">
{{ slotProps.childData.Name}}
{{ slotProps.childData.Age}}
</zizujian>
默认插槽也可以不写default
//父组件中
<zizujian v-slot="slotProps">
{{ slotProps.childData.Name}}
{{ slotProps.childData.Age}}
</zizujian>
4.解构插槽
//子组件中
<template>
<div>
<slot v-bind:childData="childUser"></slot>
</div>
</template>
<script>
export default {
data() {
return {
childUser: { Name:"Tom", Age:23 }
}
}
</script>
//父组件中
<zizujian v-slot="{childData}">
{{ childData.Name}}
{{ childData.Age}}
</zizujian>
将 childData重命名为 person
//父组件中
<zizujian v-slot="{childData:person}">
{{ person.Name}}
{{ person.Age}}
</zizujian>
也可以定义默认内容,用于插槽 prop 是 undefined 的情形
//父组件中
<zizujian v-slot="{childData= { Name: 'Guest' }}">
{{ childData.Name }}
</zizujian>