我们来看下 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','