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

相关推荐
KaMeidebaby4 小时前
卡梅德生物技术快报|PD1 单克隆抗体定制配套 N 糖全谱质控开发
前端·人工智能·算法·数据挖掘·数据分析
nuIl5 小时前
实现一个 Coding Agent(3):工具调用
前端·agent·cursor
nuIl5 小时前
实现一个 Coding Agent(4):ReAct 循环
前端·agent·cursor
nuIl5 小时前
实现一个 Coding Agent(1):一次 LLM 调用
前端·agent·cursor
nuIl5 小时前
实现一个 Coding Agent(2):让 LLM 流式响应
前端·agent·cursor
copyer_xyf5 小时前
Python 异常处理
前端·后端·python
sugar__salt5 小时前
从栈队列数据结构到JS原型面向对象全解
前端·javascript·数据结构
MageGojo6 小时前
随机文案模块怎么做?从接口封装到前端展示的完整实现思路
javascript·前端开发·api接口·后端开发·随机文案
独特的螺狮粉6 小时前
篮球集训班器具管理系统 - 鸿蒙PC Electron框架完整技术实现指南
前端·javascript·华为·electron·前端框架·开源·鸿蒙
小妖6666 小时前
js 生成随机数技巧 Math.random().toString(36)
javascript·随机数