在 Vue 中,使用 $attrs 构建高级组件

我们来看下 Vue3 中的 $attrs 属性。首先,我们会介绍它的用途以及它的实现与 Vue2 有哪些不两同点,并通过事例来加深对它的理解。

真正理解了 $attrs 属性有助于我们构建易于使用和可扩展的高级组件

什么是 $attrs

$attrs 定义, Vue2 与 Vue3 是不一样的,这里我们主要来介绍 Vue3 的版本:

$attrs 对象包含了除组件所声明的 props 和 emits 之外的所有其他 attribute,例如 class,style,v-on 监听器等等。

$attrs 也可以被看作是一个安全网,它可以捕获任何我们没有在组件中声明的东西。我们考虑一个只有一个属性和事件处理程序的组件,如下所示:

<template><h1 @click="$emit('custom', '改变标题')">{
  { title }}</h1>
</template>
<script> export default {name: 'Example',props: ['title'],emits: ['custom'],
} </script> 

如果在父组件中像下面这样实例化上面的组件:

<template><div id="app"><SimpleEventid="myId"class="myClass"data-cy="cypress-testing"@blur="onBlur"title="测试$attrs"description="没有声明 props"@custom="onCustom"/></div>
</template>

<script setup>
import SimpleEvent from './components/Button.vue'

const onBlur = () => {// todo
}
const onCustom = () => {// todo
}

</script> 

如果在组件中把 $attrs 打印出来,我们会得到如下内容:

{id: 'myId',class: 'myClass','
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值