vue3 学习笔记12 – 插槽的使用
插槽(Slots)是一种让父组件能够向子组件传递标记的方法。通过定义插槽,子组件可以预留出可由父组件控制的区域,这样父组件就可以向这些区域填充自己的内容。
假设我们有一个父组件 ParentComponent 和一个子组件 ChildComponent
默认插槽(Default Slot)
默认插槽是最基本的插槽形式,允许父组件在子组件中插入任意内容,而子组件则可以通过 来渲染这些内容。
- ParentComponent.vue
<template><div><h2>Parent Component</h2><ChildComponent><!-- 这里是默认插槽 --><p>Content inside parent component</p></ChildComponent></div>
</template><script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
</script>
- ChildComponent.vue
<template><div><h3>Child Component</h3><slot></slot></div>
</template><script setup lang="ts">
// TypeScript setup syntax
</script>
- 上述例子
- ParentComponent 包含了 ChildComponent,并传递了一些内容作为默认插槽。
- ChildComponent 中使用了 来显示来自父组件的内容。
具名插槽(Named Slots)
具名插槽允许父组件在子组件中定义多个插槽位置,使得父组件可以将不同的内容分发到不同的插槽中。这种方式特别适合需要布局或者结构化控制的场景。
- ParentComponent.vue
<template><div><h2>Parent Component</h2><ChildComponent><!-- 具名插槽 --><template #header><h3>Header in Parent</h3></template><template #footer><p>Footer in Parent</p></template></ChildComponent></div>
</template><script setup lang="ts">
import ChildComponent from './ChildComponent.vue';
</script>
- ChildComponent.vue
<template><div><h3>Child Component</h3><slot name="header"></slot><slot name="footer"></slot></div>
</template><script setup lang="ts">
// TypeScript setup syntax
</script>
- 上述例子
- ParentComponent 通过使用 <template #header> 和 <template #footer> 来定义具名插槽的内容
- ChildComponent 中使用了 和 来渲染具名插槽的内容。
作用域插槽
子组件向父组件传递数据的一种形式,子组件在具名标签或者匿名标签上绑定数据,父组件在标签上获取数据
- ParentComponent.vue
<template><div><ChildComponent v-slot="{ text,count }"><div>{{ text }}---{{ count }}</div></ChildComponent></div>
</template><script setup lang="ts">
import ChildComponent from './ChildComponent.vue';const message = 'Hello from Parent';
</script>
- ChildComponent.vue
<template><div><p>我是子组件</p><slot text="我是子组件" :count="1"></slot></div>
</template>