Preface
For third-party components, how to elegantly extend the functions while maintaining the original functions of the third-party components (properties, events, slots, methods)?
Take Element Plus’ el-input as an example:
Most likely you have played like this before, encapsulating a MyInput component and putting the props, events and slots to be used . Write the methods again according to your own needs:
// MyInput.vue <template> <div class="my-input"> <el-input v-model="inputVal" :clearable="clearable" @clear="clear"> <template #prefix> <slot name="prefix"></slot> </template> <template #suffix> <slot name="suffix"></slot> </template> </el-input> </div> </template> <script setup> import { computed } from 'vue' const props = defineProps({ modelValue: { type: String, default: '' }, clearable: { type: Boolean, default: false } }) const emits = defineEmits(['update:modelValue', 'clear']) const inputVal = computed({ get: () => props.modelValue, set: (val) => { emits('update:modelValue', val) } }) const clear = () => { emits('clear') } </script>
But after a period of time, the requirements change, and other functions of the el-input component need to be added to the MyInput component. The el-input component has a total of 20 There are multiple attributes, 5 events, and 4 slots. What should we do? Should we pass them in one by one? This is not only cumbersome but also has poor readability.
In Vue2, we can handle it like this, click here to view the encapsulation of Vue third-party components
This article is to help you migrate knowledge and explore how to use Vue3 CompositionAPI to encapsulate elegantly Third-party components~
1. For the property props and events of third-party components
In Vue2
$attrs: includes the parent role Attribute bindings (except class and style) in the domain that are not recognized (and obtained) as props. When a component does not declare any props, all parent scope bindings (except class and style) will be included here, and internal components can be passed in via v-bind="$attrs"
-
$listeners: Contains v-on event listeners in the parent scope (excluding .native modifiers). It can pass v-on="$listeners" to pass in internal components
and in Vue3
$attrs: contains the parent role Attribute bindings and events (including class, style and custom events) that are not used as component props or custom events in the domain can also be passed into internal components through v-bind="$attrs".
$listeners object has been removed in Vue 3. Event listeners are now part of $attrs.
The auxiliary function useAttrs in
//MyInput.vue <template> <div class="my-input"> <el-input v-bind="attrs"></el-input> </div> </template> <script setup> import { useAttrs } from 'vue' const attrs = useAttrs() </script>
Of course, this is not enough. Just writing like this, the attributes we bind (including class and style) will also take effect on the root element (the above example is the Dom node with class="my-input"). To prevent this default behavior, we need to set inheritAttrs to false.
Let’s take a look at the Vue3 document’s explanation of inheritAttrs
By default, attribute bindings in the parent scope that are not recognized as props will be “rolled back” and Applies to the root element of a child component as a normal HTML attribute. When writing a component that wraps a target element or another component, this may not always conform to the expected behavior. By setting inheritAttrs to false, these default behaviors will be removed. These attributes can be made effective through instance property $attrs, and can be explicitly bound to non-root elements through v-bind.
So, we can write the following code for processing the property props and events of third-party components:
// MyInput.vue <template> <div class="my-input"> <el-input v-bind="attrs"></el-input> </div> </template> <script> export default { name: 'MyInput', inheritAttrs: false } </script> <script setup> import { useAttrs } from 'vue' const attrs = useAttrs() </script>
2. For the slots of third-party components
Vue3 Medium
#$slots: We can get the slot passed in by the parent component
$scopedSlots has been removed from Vue3, all Slots are exposed as functions through $slots
The auxiliary function useSlots in
Based on the above points, if we do not add additional slots to the packaging of third-party components, and the slots of third-party components are in the same dom node, we also have a A clever encapsulation method????, get the name of the slot by traversing $slots, and dynamically add the slot of the subcomponent:
//MyInput.vue <template> <div class="my-input"> <el-input v-bind="attrs"> <template v-for="k in Object.keys(slots)" #[k] :key="k"> <slot :name="k"></slot> </template> </el-input> </div> </template> <script> export default { name: 'MyInput', inheritAttrs: false } </script> <script setup> import { useAttrs, useSlots } from 'vue' const attrs = useAttrs() const slots = useSlots() </script>
If the above conditions are not met, we have to be honest. Manually add the required third-party component slots in the component~
3. Methods for third-party components
For the methods of third-party components, we implement them through ref. First, add a ref="elInputRef" attribute to the el-input component in the MyInput component, and then expose elInputRef to the parent component through defineExpose.
Subcomponent: MyInput.vue
// MyInput.vue <template> <div class="my-input"> <el-input v-bind="attrs" ref="elInputRef"> <template v-for="k in Object.keys(slots)" #[k] :key="k"> <slot :name="k"></slot> </template> </el-input> </div> </template> <script> export default { name: 'MyInput', inheritAttrs: false } </script> <script setup> import { useAttrs, useSlots } from 'vue' const attrs = useAttrs() const slots = useSlots() const elInputRef = ref(null) defineExpose({ elInputRef // <script setup>的组件里的属性默认是关闭的,需通过defineExpose暴露出去才能被调用 }) </script>
Parent page: The calling code of Index.vue is as follows:
// Index.vue <template> <my-input v-model='input' ref="myInput"> <template #prefix>姓名</template> </my-input> </template> <script setup> import MyInput from './components/MyInput.vue' import { ref, onMounted } from 'vue' const input = ref('') const myInput = ref(null) // 组件实例 onMounted(()=> { myInput.value.elInputRef.focus() // 初始化时调用elInputRef实例的focus方法 }) </script>
The above is the detailed content of How Vue3 Composition API elegantly encapsulates third-party components. For more information, please follow other related articles on the PHP Chinese website!

提到API开发,你可能会想到DjangoRESTFramework,Flask,FastAPI,没错,它们完全可以用来编写API,不过,今天分享的这个框架可以让你更快把现有的函数转化为API,它就是Sanic。Sanic简介Sanic[1],是Python3.7+Web服务器和Web框架,旨在提高性能。它允许使用Python3.5中添加的async/await语法,这可以有效避免阻塞从而达到提升响应速度的目的。Sanic致力于提供一种简单且快速,集创建和启动于一体的方法

XXL-JOB描述XXL-JOB是一个轻量级分布式任务调度平台,其核心设计目标是开发迅速、学习简单、轻量级、易扩展。现已开放源代码并接入多家公司线上产品线,开箱即用。一、漏洞详情此次漏洞核心问题是GLUE模式。XXL-JOB通过“GLUE模式”支持多语言以及脚本任务,该模式任务特点如下:●多语言支持:支持Java、Shell、Python、NodeJS、PHP、PowerShell……等类型。●WebIDE:任务以源码方式维护在调度中心,支持通过WebIDE在线开发、维护。●动态生效:用户在线通

随着网络技术的发展,Web应用程序和API应用程序越来越普遍。为了访问这些应用程序,需要使用API客户端库。在PHP中,Guzzle是一个广受欢迎的API客户端库,它提供了许多功能,使得在PHP中访问Web服务和API变得更加容易。Guzzle库的主要目标是提供一个简单而又强大的HTTP客户端,它可以处理任何形式的HTTP请求和响应,并且支持并发请求处理。在

机器人也能干咖啡师的活了!比如让它把奶泡和咖啡搅拌均匀,效果是这样的:然后上点难度,做杯拿铁,再用搅拌棒做个图案,也是轻松拿下:这些是在已被ICLR 2023接收为Spotlight的一项研究基础上做到的,他们推出了提出流体操控新基准FluidLab以及多材料可微物理引擎FluidEngine。研究团队成员分别来自CMU、达特茅斯学院、哥伦比亚大学、MIT、MIT-IBM Watson AI Lab、马萨诸塞大学阿默斯特分校。在FluidLab的加持下,未来机器人处理更多复杂场景下的流体工作也都

前言对于第三方组件,如何在保持第三方组件原有功能(属性props、事件events、插槽slots、方法methods)的基础上,优雅地进行功能的扩展了?以ElementPlus的el-input为例:很有可能你以前是这样玩的,封装一个MyInput组件,把要使用的属性props、事件events和插槽slots、方法methods根据自己的需要再写一遍://MyInput.vueimport{computed}from'vue'constprops=define

本篇文章给大家带来了关于API的相关知识,其中主要介绍了设计API需要注意哪些地方?怎么设计一个优雅的API接口,感兴趣的朋友,下面一起来看一下吧,希望对大家有帮助。

当您的WindowsPC出现网络问题时,问题出在哪里并不总是很明显。很容易想象您的ISP有问题。然而,Windows笔记本电脑上的网络并不总是顺畅的,Windows11中的许多东西可能会突然导致Wi-Fi网络中断。随机消失的Wi-Fi网络是Windows笔记本电脑上报告最多的问题之一。网络问题的原因各不相同,也可能因Microsoft的驱动程序或Windows而发生。Windows是大多数情况下的问题,建议使用内置的网络故障排除程序。在Windows11

SpringBoot的API加密对接在项目中,为了保证数据的安全,我们常常会对传递的数据进行加密。常用的加密算法包括对称加密(AES)和非对称加密(RSA),博主选取码云上最简单的API加密项目进行下面的讲解。下面请出我们的最亮的项目rsa-encrypt-body-spring-boot项目介绍该项目使用RSA加密方式对API接口返回的数据加密,让API数据更加安全。别人无法对提供的数据进行破解。SpringBoot接口加密,可以对返回值、参数值通过注解的方式自动加解密。什么是RSA加密首先我


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor
