Vue3 中插槽的使用,插槽是 Vue 中的一个特别特性,插槽就是模版内容。例如<h1>标题 1</h1>标题 1 就是插槽,Vue 是无法识别模板内容的,只能通过属性进行传递。Slot 主要包括默认、具名和作用域。Slot开发起来难度不大,看如下代码:
插槽
首先在组件中插槽定义:
 <slot></slot>父组件不做任何指定时,所有内容均显示在默认插槽中。
 <slot name="slot1"></slot>父组件中需要指定名字
 作用域插槽是一种子组件向父组件传递参数的方式,默认情况下父组件插槽内容只能使用父组件定义的变量,作用域插槽可以将子组件中的参数向父组件进行传递。
<template>
    <slot></slot>
    <slot name="slot1"></slot>
    <slot name="slot2" v-bind="params"></slot>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
type user = {
    "name":string
}
const params = reactive<user>({name:"www"})
</script>
 
在父组件中使用插槽。
<template>
<SlotView>
    <div>默认 Slot</div>
    <template #slot1>
        <div>具名 Slot</div>
    </template>
    <template #slot2="params">
        <div>作用域插槽 {{params.name}}</div>
    </template>
</SlotView>
</template>
<script setup lang="ts">
import { reactive } from 'vue';
import SlotView from './slots.vue'
const params = reactive({name:"参数 name"})
</script>
<style>
.c1{
    background-color: royalblue;
}
</style>
 

总结
Vue 中插槽使用很普遍,在各类组件库中都很常见。



















