useAttrs是vue3新增的API,可以帮我们更方便的处理父组件传过来的props属性,但使用useAttrs也有一些需要注意的点。
#使用
在开发中我们可以使用useAttrs来接收父组件传过来的props或者emit属性和事件,可以不需要另外声明props或者emit。
举例如下:
子组件–
<template>
<div>
<h2>{{ title }}</h2>
<p>{{ content }}</p>
<button @click="onClick">点击</button>
</div>
</template>
<script setup>
import { useAttrs } from 'vue'
export default {
setup() {
const { title, content, onClick } = useAttrs()
return { title, content, onClick }
}
}
</script>
父组件传值:
<template>
<div>
<MyComponent title="标题" content="内容" @click="handleClick" />
</div>
</template>
<script>
import MyComponent from '@/components/MyComponent.vue'
export default {
components: { MyComponent },
methods: {
handleClick() {
console.log('点击事件触发')
}
}
}
</script>
#useAttrs和defineProps对比
1、useAttrs 方法能够接收到所有属性,包括未在组件中声明的属性,但不能够对接收到的属性进行类型校验和默认值设置。
2、defineProps 方法只能接收到在组件中声明的属性,但能够对接收到的属性进行类型校验和默认值设置,使得组件能够更加健壮。
<template>
<div>Hello, {{ name }}!</div>
</template>
<script setup>
import { defineProps } from 'vue'
const props = defineProps({
name: {
type: String,
default: 'world'
}
})
</script>
#defineProps比useAttrs优先级高
在使用 useAttrs 和 defineProps 接收属性时,使用 defineProps 接收的属性会优先级更高,因为它可以对每个属性进行类型验证和默认值设置,同时这些属性会被添加到组件实例的 $props 属性中。
而使用 useAttrs 接收的属性只是简单地返回所有传递的属性,不能对其进行类型验证和默认值设置,同时这些属性不会被添加到组件实例的 $props 属性中。
<template>
<div>
props.sex: {{ $props.sex }}<br>
attrs.sex: {{ $attrs.sex }}
</div>
</template>
<script setup>
import { useAttrs } from 'vue'
const props = defineProps({
sex: String
})
const attrs = useAttrs()
console.log(attrs.sex) // 'undefined'
</script>