Vue3 插槽复习
1. 默认插槽
// 父组件 <SlotComp msg="Vite + Vue">
// 或者此处使用 具名插槽 但是插槽名为 default
// v-slot:default #default 222 </SlotComp> // 子组件 // 只要在组件内部使用<slot>标签包裹内容即可 标签内的内容为默认内容 <template> <h1>{{ msg }}</h1> <button> <slot>111</slot> </button> </template>
2. 具名插槽
// 父组件 // 使用 template 标签 并配合 v-slot:"name" 为插槽命名 <SlotComp msg="Vite + Vue">
// v-slot 可以用 # 代替 所以下面可以用
// <template #header> 代替 <template v-slot:header> 这是一条头部插槽 </template> </SlotComp> // 子组件 // 使用 slot 标签 并配合 name="插槽名" 进行绑定 <template> <h1>{{ msg }}</h1> <slot name="header"></slot> </template>
3. 条件插槽
// 父组件 // 与具名插槽一致 主要区别在于子组件的条件判断 <SlotComp msg="Vite + Vue"> <template #header> 这是一条头部插槽 </template> </SlotComp> // 子组件 // 使用 v-if="$slots.插槽名" 来为插槽配置样式 <template> <div v-if="$slots.header" class="slot-header"> <slot name="header"></slot> </div> </template>
4. 动态插槽名
// 父组件 // 使用 [] 包裹插槽名 可以使用变量 header 作为插槽名 <SlotComp msg="Vite + Vue"> // <template v-slot:[header]> <template #[header]> 这是一条头部插槽 </template> </SlotComp>
5. 作用域插槽
一般情况下 插槽只能使用到父组件的变量 无法获取到子组件中的变量
当我们需要使用子组件变量 或者需要 子组件传给父组件时 这就是作用域插槽的应用场景
//默认插槽 // 与具名插槽写法略有差异 基本一致 <SlotComp v-slot="headerProps">
// 支持解构
// <SlotComp v-slot="{slotValue, slotText}"> <p>子组件的值: {{ headerProps.slotValue }}</p> <p>子组件的内容: {{ headerProps.slotText }}</p> </SlotComp> //具名插槽 // 父组件 // 使用 #header="子组件Props" 来接收子组件传过来的数据 <template #header="headerProps"> <p>子组件的值: {{ headerProps.slotValue }}</p> <p>子组件的内容: {{ headerProps.slotText }}</p> </template> // 子组件 const slotValue = ref(0) const slotText = ref('子组件内容') <slot name="header" :slotValue="slotValue" :slotText="slotText" ></slot>
当默认插槽与具名插槽,则需要为默认插槽使用显式的 <template> 标签。尝试直接为组件添加 v-slot 指令将导致编译错误。这是为了避免因默认插槽的 props 的作用域而困惑。
浙公网安备 33010602011771号