vue3中$attrs与inheritAttrs的使用

Vue 3 引入了一些新特性和改进,其中之一就是对 $attrs 的处理方式。在 Vue 2 中,$attrs 包含了父组件传递给子组件的属性,但不包括子组件已经声明的 props。在 Vue 3 中,$attrs 的行为有所变化:

  1. 默认情况下,$attrs 包含所有未被子组件的 props 声明的属性。也就是说,如果父组件传递了多个属性给子组件,即使子组件只声明了其中的一部分作为 props,$attrs 也会包含所有未声明的属性。
<!-- 父组件 -->
<template>
  <MyComponent custom-prop="value" other-attr="otherValue" />
</template>
<!-- 子组件 -->
<template>
  <div>Custom prop: {{ customProp }}</div>
  <!-- $attrs 包含 other-attr="otherValue" -->
</template>

<script setup>
import { defineProps } from 'vue';

const props = defineProps({
  customProp: String
});
</script>
  1. vue3中 $attrs 包含了事件监听器。在 Vue 2 中,事件监听器不会包含在 $attrs 中。但在 Vue 3 中,如果父组件传递了事件监听器给子组件,这些监听器也会包含在 $attrs 中。
<!-- 父组件 -->
<template>
  <MyComponent @custom-event="handleCustomEvent" />
</template>

<script setup>
const handleCustomEvent() {
    console.log('Custom event triggered');
} 
</script>
<!-- 子组件 -->
<template>
  <button @click="$attrs.onClick">Trigger Event</button>
  <!-- $attrs 包含 @custom-event="handleCustomEvent" -->
</template>

<script setup>
import { useAttrs } from 'vue';

const attrs = useAttrs();
</script>
  1. vue3中 $attrs 是一个响应式对象。在 Vue 2 中,$attrs 是一个静态对象,不会随着父组件属性的变化而更新。但在 Vue 3 中,$attrs 是响应式的,如果父组件的属性发生变化,$attrs 也会相应地更新。
<!-- 父组件 -->
<template>
  <div>
    <button @click="toggleAttr">Toggle attr</button>
    <MyComponent :dynamic-attr="dynamicAttr" />
  </div>
</template>

<script setup>
import { ref } from 'vue';

const dynamicAttr = ref('initial');

function toggleAttr() {
  dynamicAttr.value = dynamicAttr.value === 'initial' ? 'updated' : 'initial';
}
</script>


<!-- 子组件 -->
<template>
  <div>Dynamic attr: {{ attrs.dynamicAttr }}</div>
</template>

<script setup>
import { useAttrs } from 'vue';

const attrs = useAttrs();
</script>
  1. vue3中 $listeners 已被删除合并到$attrs。在 Vue 2 中,$listeners 包含了父组件传递给子组件的所有事件监听器。但在 Vue 3 中,$listeners 被移除,所有的属性和事件监听器都包含在 $attrs 中。
<!-- 子组件 -->
<template>
  <button v-on="attrs">Click me</button>
  <!-- 所有事件监听器都会应用到这个按钮上 -->
</template>

<script setup>
import { useAttrs } from 'vue';

const attrs = useAttrs();
</script>
  1. inheritAttrs 选项。在 Vue 2 中,inheritAttrs 是一个布尔值,用于控制是否将 $attrs 中的属性自动应用到子组件的根元素上。在 Vue 3 中,inheritAttrs 仍然是一个选项,但它现在默认为 false,这意味着属性不会自动应用,除非你明确地使用它们。
<!-- 子组件 -->
<template>
  <div v-bind="$attrs">
    <!-- 属性将应用到这个div上 -->
  </div>
</template>

<script setup>
import { defineProps, withDefaults } from 'vue';

const props = withDefaults(defineProps({}), {});
</script>
  1. v-on="$attrs" 用法。在 Vue 3 中,你可以使用 v-on="$attrs" 将所有的事件监听器应用到一个元素上。
<!-- 子组件 -->
<template>
  <button v-on="$attrs">Click me</button>
  <!-- 所有事件监听器都会应用到这个按钮上 -->
</template>

<script setup>
// 无需额外的脚本,直接使用$attrs即可
</script>
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值