当前位置: 首页 > news >正文

vue-插槽作用域实用场景

vue-插槽作用域实用场景

  • 1.插槽
    • 1.1 自定义列表渲染
    • 1.2 数据表格组件
    • 1.3 树形组件
    • 1.4 表单验证组件
    • 1.5 无限滚动组件

1.插槽

插槽感觉知道有这个东西,但是挺少用过的,每次看到基本都会再去看一遍用法和概念。但是在项目里,自己还是没有用到过。总结下一些可能用到的场景,下次直接这样写了。

1.1 自定义列表渲染

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { reactive } from 'vue';
const myItems = reactive([{name: 'A',age: 18},{name: 'B',age: 19},{name: 'C',age: 20}
]
)
</script>
<template><HelloWorld :items="myItems"><template v-slot:default="slotProps"><span>{{ slotProps.item.name }}</span><button @click="doSomething(slotProps.item)">操作</button></template></HelloWorld>
</template><script setup>
import { defineProps } from 'vue';defineProps({items: {type: Array,default: () => []}
})
</script>
<template><ul><li v-for="item in items" :key="item.id"><slot :item="item"></slot></li></ul>
</template>

效果:
在这里插入图片描述
拓展性很强。

1.2 数据表格组件

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import { reactive } from 'vue';
const tableData = reactive([{name: 'A',age: 18},{name: 'B',age: 19},{name: 'C',age: 20}]
)const columns = reactive([{label: '姓名',key: 'name'},{label: '年龄',key: 'age'},{label: '性别',key: 'sex'},{ key: 'actions', label: '操作' }]
)
</script>
<template><HelloWorld :columns="columns" :data="tableData"><template v-slot:actions="{ row }"><button @click="edit(row)">编辑</button><button @click="del(row)">删除</button></template></HelloWorld>
</template><template><table><thead><tr><th v-for="column in columns" :key="column.key">{{ column.label }}</th></tr></thead><tbody><tr v-for="row in data" :key="row.id"><td v-for="column in columns" :key="column.key"><slot :name="column.key" :row="row">{{ row[column.key] }}</slot></td></tr></tbody></table>
</template><script setup>
import { defineProps } from 'vue';
defineProps({columns: Array,data: Array,
});
</script>

效果:
在这里插入图片描述

1.3 树形组件

<template><div class="tree-node"><slot :node="node" :toggle="toggle" :expandTree="expandTree" name="trangle"><span v-if="node.children.length > 0" @click="toggle">{{ expanded ? '▼' : '▶' }}</span></slot><slot :node="node" :toggle="toggle" :expandTree="expandTree"><div>{{ node.label }}</div></slot><div v-if="expanded" class="tree-node-children"><HelloWorld v-for="child in node.children" :key="child.id" :node="child"><template v-slot="childSlotProps"><slot v-bind="childSlotProps"></slot></template></HelloWorld></div></div>
</template>
<script setup>
import HelloWorld from './HelloWorld.vue'
import { defineProps, ref } from 'vue';
const props = defineProps({node: {type: Object,required: true}
})
const expanded = ref(false)
const toggle = () => {console.log(999)expanded.value = !expanded.value
}
const expandTree = () => {expanded.value = true
}
</script>
<style>
.tree-node {position: relative;cursor: pointer;
}.tree-node-children {position: relative;padding-left: 20px;/* 这个值决定了每一层的缩进量 */
}.tree-node>span {margin-left: 0;
}
</style><script setup>
import HelloWorld from './components/HelloWorld.vue'
import { reactive } from 'vue';const rootNode = reactive({id: 1,label: '根节点',children: [{id: 2, label: '子节点1', children: [{ id: 3, label: '子节点1-1', children: [] }]},{ id: 4, label: '子节点2', children: [] }]
})const addChild = (node, expandTree) => {const newId = Date.now()expandTree()node.children.push({id: newId,label: `新子节点${newId}`,children: []})
}
</script>
<template><HelloWorld :node="rootNode"><template v-slot="{ node, toggle, expandTree }"><span @click="toggle">{{ node.label }}</span><button @click="addChild(node, expandTree)">添加子节点</button></template></HelloWorld>
</template>

效果:
在这里插入图片描述

1.4 表单验证组件

<script setup>
import { ref, watch, defineProps, defineEmits } from 'vue'const props = defineProps({rules: {type: Array,default: () => []},modelValue: {type: String,default: ''}
})const emit = defineEmits(['update:modelValue'])const value = ref(props.modelValue)
const error = ref('')const validate = () => {for (const rule of props.rules) {if (!rule.validate(value.value)) {error.value = rule.messagereturn false}}error.value = ''return true
}watch(() => props.modelValue, (newValue) => {value.value = newValue
})watch(value, (newValue) => {emit('update:modelValue', newValue)
})
</script><template><div class="a"><slot :value="value" :error="error" :validate="validate"></slot><span v-if="error">{{ error }}</span></div>
</template>
<style lang="scss" scoped>
.a{position: relative;span{color: red;position: absolute;left: 0;bottom: -24px;font-size: 14px;}
}</style>//使用
<script setup>
import FormField from './components/HelloWorld.vue'
import { ref } from 'vue';const email = ref('')const emailRules = [{validate: (value) => /.+@.+\..+/.test(value),message: '请输入有效的电子邮件地址'}
]
</script>
<template><FormField :rules="emailRules" v-model="email"><template v-slot="{ value, error, validate }">邮箱<input :value="value" @input="$event => { email = $event.target.value; validate(); }":class="{ 'is-invalid': error }" /></template></FormField>
</template><style >
input{outline: none;
}
.is-invalid:focus {border-color: red;
}
</style>

效果:
在这里插入图片描述

1.5 无限滚动组件


<script setup>
import { ref, onMounted, defineProps } from 'vue'const props = defineProps({fetchItems: {type: Function,required: true}
})const visibleItems = ref([])
const loading = ref(false)const handleScroll = async (event) => {const { scrollTop, scrollHeight, clientHeight } = event.targetif (scrollTop + clientHeight >= scrollHeight - 20 && !loading.value) {loading.value = trueconst newItems = await props.fetchItems()visibleItems.value = [...visibleItems.value, ...newItems]loading.value = false}
}onMounted(async () => {visibleItems.value = await props.fetchItems()
})
</script><template><div @scroll="handleScroll" style="height: 200px; overflow-y: auto;"><slot :items="visibleItems"></slot><div v-if="loading">加载中...</div></div>
</template>//使用
<script setup>
import InfiniteScroll from './components/HelloWorld.vue'
import { ref } from 'vue';let page = 0
const fetchMoreItems = async () => {// 模拟API调用await new Promise(resolve => setTimeout(resolve, 1000))page++return Array.from({ length: 10 }, (_, i) => ({id: page * 10 + i,content: `Item ${page * 10 + i}`}))
}
</script>
<template><InfiniteScroll :fetch-items="fetchMoreItems"><template #default="{ items }"><div v-for="item in items" :key="item.id">{{ item.content }}</div></template></InfiniteScroll>
</template>

相关文章:

vue-插槽作用域实用场景

vue-插槽作用域实用场景 1.插槽1.1 自定义列表渲染1.2 数据表格组件1.3 树形组件1.4 表单验证组件1.5 无限滚动组件 1.插槽 插槽感觉知道有这个东西&#xff0c;但是挺少用过的&#xff0c;每次看到基本都会再去看一遍用法和概念。但是在项目里&#xff0c;自己还是没有用到过…...

Prometheus+Grafana 监控 K8S Ingress-Ningx Controller

文章目录 一、prometheus中添加ingress-nginx的服务发现配置二、ingress-nginx controller的service添加端口暴露监控指标三、grafana添加ingress-nginx controller的监控模版 ingress-nginx默认是没有开启监控指标的&#xff0c;需要我们在ingress-nginx controller的svc里面开…...

如何在Visual Studio 2019中创建.Net Core WPF工程

如何在Visual Studio 2019中创建.Net Core WPF工程 打开Visual Studio 2019&#xff0c;选择Create a new project 选择WPF App(.Net Core) 输入项目名称和位置&#xff0c;单击Create 这样我们就创建好了一个WPF工程 工程文件说明 Dependencies 当前项目所使用的依赖库&…...

自然语言处理(NLP)论文数量的十年趋势:2014-2024

引言 近年来&#xff0c;自然语言处理&#xff08;NLP&#xff09;已成为人工智能&#xff08;AI&#xff09;和数据科学领域中的关键技术之一。随着数据规模的不断扩大和计算能力的提升&#xff0c;NLP技术从学术研究走向了广泛的实际应用。通过观察过去十年&#xff08;2014…...

.net core API中使用LiteDB

LiteDB介绍 LiteDB 是一个小巧、快速和轻量级的 .NET NoSQL 嵌入式数据库。 无服务器的 NoSQL 文档存储简单的 API&#xff0c;类似于 MongoDB100% 的 C# 代码支持 .NET 4.5 / NETStandard 1.3/2.0&#xff0c;以单个 DLL&#xff08;不到 450KB&#xff09;形式提供线程安全…...

YOLO_V8分割

YOLO_V8分割 YOLO安装 pip install ultralytics YOLO的数据集转化看csdn 数据标注EIseg EIseg这块&#xff0c;正常安装就好&#xff0c;但是numpy和各类包都容易有冲突&#xff0c;python版本装第一点 数据标注过程中&#xff0c;记得把JSON和COCO都点上&#xff0c;把自…...

根据请求错误的状态码判断代理配置问题

SafeLine&#xff0c;中文名 “雷池”&#xff0c;是一款简单好用, 效果突出的 Web 应用防火墙(WAF)&#xff0c;可以保护 Web 服务不受黑客攻击。 雷池通过过滤和监控 Web 应用与互联网之间的 HTTP 流量来保护 Web 服务。可以保护 Web 服务免受 SQL 注入、XSS、 代码注入、命…...

Python 网络爬虫高阶用法

网络爬虫成为了自动化数据抓取的核心工具。Python 拥有强大的第三方库支持&#xff0c;在网络爬虫领域的应用尤为广泛。本文将深入探讨 Python 网络爬虫的高阶用法&#xff0c;包括处理反爬虫机制、动态网页抓取、分布式爬虫以及并发和异步爬虫等技术。以下内容结合最新技术发展…...

芯片Tapeout前GDS Review | Calibre中如何切出gds中指定区域版图?

在SoC芯片实现阶段我们会用到很多模拟IP&#xff0c;IO。对于这类模拟IP相关的电源连接&#xff0c;ESD保护电路连接&#xff0c;信号线连接都需要跟IP Vendor进行Review。但芯片整体版图涉及商业机密&#xff0c;我们不希望整个芯片的版图被各大vendor看到&#xff0c;因此我们…...

43 | 单例模式(下):如何设计实现一个集群环境下的分布式单例模式?

上两篇文章中&#xff0c;我们针对单例模式&#xff0c;讲解了单例的应用场景、几种常见的代码实现和存在的问题&#xff0c;并粗略给出了替换单例模式的方法&#xff0c;比如工厂模式、IOC 容器。今天&#xff0c;我们再进一步扩展延伸一下&#xff0c;一块讨论一下下面这几个…...

PHP如何解决异常处理

在PHP中&#xff0c;异常处理是通过使用try、catch、throw以及finally这几个关键字来实现的。以下是一个简单的介绍和示例&#xff1a; 异常处理的基本步骤 抛出异常&#xff1a; 使用throw关键字抛出一个异常对象。异常对象通常是Exception类或其子类的实例。 捕获异常&…...

C++ socket编程(3)

前面文章&#xff0c;介绍了一个简单socket通讯Demo&#xff0c; 客户端和服务器进行简单的交互。两个代码都很简单&#xff0c;如果情况一复杂&#xff0c;就会出错。这节我们把代码完善一下&#xff0c;实现一个客户端输入&#xff0c;发送&#xff0c;服务器echo的交互。本文…...

Collection-LinkedList源码解析

文章目录 概述LinkedList实现底层数据结构构造函数getFirst(), getLast()removeFirst(), removeLast(), remove(e), remove(index)add()addAll()clear()Positional Access 方法查找操作 概述 LinkedList同时实现了List接口和Deque接口&#xff0c;也就是说它既可以看作一个顺序…...

vue判断对象数组里是否有重复数据

TOCvue判断对象数组里是否有重复数据 try {//通过产品编码赛选出新的数组 在比较let names this.goodsJson.map(item > item["productCode"]);let nameSet new Set(names)if (nameSet.size ! names.length) {this.$message({message: 警告&#xff01;产品选项…...

CSS 3D转换

在 CSS 中&#xff0c;除了可以对页面中的元素进行 2D 转换外&#xff0c;您也可以对象元素进行 3D转换&#xff08;将页面看作是一个三维空间来对页面中的元素进行移动、旋转、缩放和倾斜等操作&#xff09;。与 2D 转换相同&#xff0c;3D 转换同样不会影响周围的元素&#x…...

51单片机数码管循环显示0~f

原理图&#xff1a; #include <reg52.h>sbit dulaP2^6;//段选信号 sbit welaP2^7;//位选信号unsigned char num;//数码管显示的数字0~funsigned char code table[]{ 0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x77,0x7c, 0x39,0x5e,0x79,0x71};//定义数码管显…...

【编程进阶知识】Java NIO:掌握高效的I/O多路复用技术

Java NIO&#xff1a;掌握高效的I/O多路复用技术 摘要&#xff1a; 本文将带你深入了解Java NIO&#xff08;New I/O&#xff09;中的Selector类&#xff0c;探索如何利用它实现高效的I/O多路复用&#xff0c;类似于Linux中的select和epoll系统调用。文章将提供详细的代码示例…...

vscode创建flutter项目,运行flutter项目

打开View&#xff08;查看&#xff09; > Command Palette...&#xff08;命令面板&#xff09;。 可以按下 Ctrl / Cmd Shift P 输入 flutter 选择Flutter: New Project 命令 按下 Enter 。选择Application 选择项目地址 输入项目名称 。按下 Enter 等待项目初始化完成 …...

STM32之CAN外设

相信大家在学习STM32系列的单片机时&#xff0c;在翻阅芯片的数据手册时&#xff0c;都会看到这么一个寄存器外设——CAN外设寄存器。那么&#xff0c;大家知道这个外设的工作原理以及该如何使用吗&#xff1f;这节的内容将会详细介绍STM32上的CAN外设&#xff0c;文章结尾附有…...

【阅读笔记】水果轻微损伤的无损检测技术应用

一、水果轻微损伤检测技术以及应用 无损检测技术顾名思义就是指在不破坏水果样品完整性的情况下对样品进行品质鉴定。目前比较常用的农产品水果类无损检测法有&#xff1a;基于红外热成像、机器视觉技术的图像处理方法、光谱检测技术、介电特性技术检测法等。 1.1 基于红外热…...

忘记7-zip密码,如何解压文件?

7z压缩包设置了密码&#xff0c;解压的时候就需要输入正确对密码才能顺利解压出文件&#xff0c;正常当我们解压文件或者删除密码的时候&#xff0c;虽然方法多&#xff0c;但是都需要输入正确的密码才能完成。忘记密码就无法进行操作。 那么&#xff0c;忘记了7z压缩包的密码…...

SpringBoot基础(一)

1.SpringBoot简介 Spring Boot是Spring社区发布的一个开源项目&#xff0c;旨在帮助开发者快速并且更简单的构建项目。它 使用习惯优于配置的理念让你的项目快速运行起来&#xff0c;使用Spring Boot很容易创建一个独立运行 &#xff08;运行jar&#xff0c;内置Servlet容器&am…...

Java智能匹配灵活用工高效人力资源管理系统小程序源码

智能匹配灵活用工高效人力资源管理系统 &#x1f4bc;&#x1f680; &#x1f680; 开篇&#xff1a;职场新风尚&#xff0c;智能匹配引领变革 在这个瞬息万变的时代&#xff0c;职场也在经历着前所未有的变革。传统的用工模式已难以满足现代企业的需求&#xff0c;而“智能匹…...

openpdf

1、简介 2、示例 2.1 引入依赖 <dependency><groupId>com.github.librepdf</groupId><artifactId>openpdf</artifactId><version>1.3.34</version></dependency><dependency><groupId>com.github.librepdf</…...

C#垃圾回收机制详解

本文详解C#垃圾回收机制。 目录 一、C#垃圾收集器定义 二、C#中的垃圾收集器特点 三、垃圾回收触发条件 四、常见的内存泄漏情况 五、高性能应用程序的垃圾回收策略 六、最佳实践和建议 七、实例 一、C#垃圾收集器定义 int、string变量,这些数据都存储在内存中,如果…...

身份证二要素核验操作指南

身份证二要素核验主要涉及验证身份证上的姓名和身份证号码这两个关键信息&#xff0c;以下是详细的操作指南&#xff1a; 一、核验流程 输入信息&#xff1a;用户在客户端&#xff08;如APP、网站等&#xff09;输入自己的姓名和身份证号码。 信息加密与传输&#xff1a;客户端…...

量子数字签名概述

我们都知道&#xff0c;基于量子力学原理研究密钥生成和使用的学科称为量子密码学。其内容包括了量子密钥分发、量子秘密共享、量子指纹识别、量子比特承诺、量子货币、秘密通信扩展量子密钥、量子安全计算、量子数字签名、量子隐性传态等。虽然各种技术发展的状态不同&#xf…...

算法题——合并 k 个升序的链表

题目描述&#xff1a; 合并 k 个升序的链表并将结果作为一个升序的链表返回其头节点。 数据范围&#xff1a;节点总数 0≤n≤50000≤n≤5000&#xff0c;每个节点的val满足 ∣val∣<1000∣val∣<1000 要求&#xff1a;时间复杂度 O(nlogn) 一、常见解法 &#xff08…...

智能制造与精益制造的模型搭建

现行制造模式分析I-痛点改善思路-管控省优四化推行...

快速生成生产级Go应用的利器——Cgapp

简介 CGAPP是一个强大的命令行工具&#xff0c;开发者通过简单的命令就可以快速搭建起一个完整的Go项目框架。这个框架不仅包括后端服务&#xff0c;还可以集成前端代码和数据库配置&#xff0c;大大简化了项目的初始化过程。 安装 安装CGAPP的过程非常简单。首先&#xff0…...