Vue3 中的插槽

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 中插槽使用很普遍,在各类组件库中都很常见。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值