在 Vue 3 中,slot 用于让组件的使用者可以向组件内部插入自定义内容。Vue 3 提供了多种声明和使用插槽的方式,下面为你详细介绍不同类型插槽的声明方法和对应的调用方式。
1. 匿名插槽
声明方法
在组件模板中直接使用 标签来定义匿名插槽,它可以接收组件使用者传入的任意内容。
<!-- MyComponent.vue -->
<template><div><h2>这是组件标题</h2><slot></slot></div>
</template>
调用方式
在使用该组件时,直接在组件标签内写入要插入的内容,这些内容会被插入到匿名插槽的位置。
<template><MyComponent><p>这是插入到匿名插槽的内容</p></MyComponent>
</template>
2. 具名插槽
声明方法
在组件模板中使用 name 属性为 标签命名,从而定义具名插槽。
<!-- MyComponent.vue -->
<template><div><header><slot name="header"></slot></header><main><slot></slot></main><footer><slot name="footer"></slot></footer></div>
</template>
调用方式
在使用组件时,使用 标签并通过 v-slot 指令指定要插入的具名插槽名称。v-slot 可以简写为 #。
<template><MyComponent><template #header><h1>这是头部内容</h1></template><p>这是插入到匿名插槽的内容</p><template #footer><p>这是底部内容</p></template></MyComponent>
</template>
3. 作用域插槽
声明方法
作用域插槽允许组件向插槽内容传递数据。在组件模板中,通过在 标签上绑定属性来传递数据。
<!-- MyComponent.vue -->
<template><div><slot :items="items"></slot></div>
</template><script setup>
import { ref } from 'vue';
const items = ref(['苹果', '香蕉', '橙子']);
</script>
调用方式
在使用组件时,通过 v-slot 指令接收传递的数据,语法为 v-slot:插槽名=“变量名”,可以使用解构赋值来获取具体的数据。
<template><MyComponent><template #default="{ items }"><ul><li v-for="item in items" :key="item">{{ item }}</li></ul></template></MyComponent>
</template>
4. 具名作用域插槽
声明方法
具名作用域插槽结合了具名插槽和作用域插槽的特点,在具名插槽的基础上传递数据。
<!-- MyComponent.vue -->
<template><div><slot name="list" :items="items"></slot></div>
</template><script setup>
import { ref } from 'vue';
const items = ref(['苹果', '香蕉', '橙子']);
</script>
调用方式
在使用组件时,使用 v-slot 指令指定具名插槽,并接收传递的数据。
<template><MyComponent><template #list="{ items }"><ul><li v-for="item in items" :key="item">{{ item }}</li></ul></template></MyComponent>
</template>
通过以上不同类型插槽的声明和调用方式,你可以在 Vue 3 中灵活地实现组件内容的自定义插入和数据传递。