Vue3 之 透传 Attributes,$attrs

Vue3 之 透传 Attributes(属性),$attrs

“透传 attribute” 指的是传递给一个组件,却没有被该组件声明为 props 或 emits 的 attribute 或者 v-on 事件监听器。最常见的例子就是 class、style 和 id。

就比如我们向一个组件传递属性,这个属性默认会绑定到这个组件里面的根元素身上

// 父组件 MyButton 内容
<button class="textCenter">
	我是父组件里面的根组件的内容
	<p>我是子组件</p>
</button>

// 一个父组件中设置了 class
<MyButton class="large" />

// 这个class 就会默认传递到这个组件里面的根元素上
// 并且属性如果组件已经存在,将会合并属性
<button class="large textCenter">
	我是父组件里面的根组件的内容
	<p>我是子组件</p>
</button>

这里, 并没有将 class 声明为一个它所接受的 prop,所以 class 被视作透传 attribute,自动透传到了 的根元素上。

同样的 v-on 绑定事件,父组件跟 组件根组件都同时监听同一个事件的话,事件触发,对应监听的方法都会执行。

// 父组件
<MyButton @click="onClick1" />

// MyButton 组件里面
<button @click="onClick2" >
	我是父组件里面的根组件的内容
	<p>我是子组件</p>
</button>

// 触发了 click 事件的话,会把 onClick1,onClick2 都一起执行

禁用 Attributes 继承

如果你不想要一个组件自动地继承 attribute,你可以在组件选项中设置 inheritAttrs: false。
在这里插入图片描述

最常见的需要禁用 attribute 继承的场景就是 attribute 需要应用在根节点以外的其他元素上。通过设置 inheritAttrs 选项为 false,你可以完全控制透传进来的 attribute 被如何使用。

这些透传进来的 attribute 可以在模板的表达式中直接用 $attrs 访问到。

// $attrs 相当于高级版 props, 可以获取到父组件传递的 class, id ,style 
<span>Fallthrough attribute: {{ $attrs }}</span>

现在我们想要父组件传递的属性,不在组件内根组件继承,在根组件里面的子组件基础

// ---MyButton 组件里面
<button class="textCenter">
	我是父组件里面的根组件的内容
	<p v-bind="$attrs">
		我是子组件,通过 this.$attrs 获取父组件属性
	</p>
</button>

export {
	// 取消默认 透传 attribute 到根组件
	inheritAtters:false
}

// ---父组件
<MyButton class="large" @click ="onClick"></MyButton>

// 实际组件里面的内容
<button class="textCenter">
	我是父组件里面的根组件的内容
	<p  class="large" @click ="onClick">
		我是子组件,通过 this.$attrs 获取父组件属性
	</p>
</button>

如果组件里面没有根节点,vue 将不会自动 attribute 透传行为,并且里面将会抛出一个警告,需要在组件中规定哪个组件使用 $attrs 透传 attribute

<!-- 父组件 -->
<CustomLayout id="custom-layout" @click="changeValue" />
<!--CustomLayout 组件内容 -->
<!-- 没有根组件,vue 不知道哪个要组件要进行继承,抛出警告 -->
<header>...</header>
<main>...</main>
<footer>...</footer>

<!--解决办法:明确规定哪个组件进行继承-->
<header>...</header>
<main v-bind="$attrs">使用 $attrs </main>
<footer>...</footer>

在 JavaScript 中访问透传 Attributes

如果需要,你可以通过 $attrs 这个实例属性来访问组件的所有透传 attribute

export default {
  created() {
    console.log(this.$attrs)
  }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值