在 Vue 3 中,props 和 attrs 是两个不同的概念,它们的主要区别在于用途和行为。以下是它们的详细区别:
1. props
-
定义:
props是组件的自定义属性,用于从父组件向子组件传递数据。 -
特点:
props是响应式的,父组件传递的数据变化会自动更新子组件中的props。props必须在子组件中显式声明(通过defineProps或props选项)。props是子组件的接口,用于定义子组件期望接收的数据。props不会包含继承的属性(如class和style),除非显式声明。
-
示例:
<script setup> const props = defineProps({ message: String, }); </script> <template> <div>{{ message }}</div> </template>父组件传递
message:<ChildComponent message="Hello, Vue 3!" />
2. attrs
-
定义:
attrs包含了所有传递给组件的非props属性,包括继承的属性(如class和style)以及未在props中声明的属性。 -
特点:
attrs是非响应式的,它只是对 DOM 属性的直接映射。attrs包含了所有未在props中声明的属性,以及继承的属性(如class和style)。- 如果需要访问
attrs,可以使用useAttrs钩子或在模板中通过v-bind="$attrs"绑定。 attrs不会自动更新,除非 DOM 属性发生变化。
-
示例:
<script setup> const attrs = useAttrs(); console.log(attrs); // 输出所有非 props 的属性 </script> <template> <div v-bind="$attrs">Attrs Example</div> </template>父组件传递未声明的属性:
<ChildComponent id="my-id" class="my-class" data-custom="value" />在子组件中,
attrs会包含id、class和data-custom。
3. 主要区别
| 特性 | props |
attrs |
|---|---|---|
| 定义 | 显式声明的属性 | 非显式声明的属性 |
| 响应式 | 是 | 否 |
| 包含内容 | 自定义属性 | 非 props 属性和继承的属性 |
| 用途 | 组件接口,用于父子组件通信 | 处理未声明的属性或 DOM 属性 |
| 访问方式 | defineProps 或 props 选项 |
useAttrs 或 $attrs |
4. 使用场景
props:当需要从父组件向子组件传递数据时使用,适合需要响应式更新的场景。attrs:当需要处理未声明的属性或继承的属性时使用,适合需要直接操作 DOM 属性的场景。
5. 注意事项
- 如果子组件没有声明
inheritAttrs: false,attrs中的属性会自动绑定到根元素上。可以通过inheritAttrs: false来禁用这一行为。 attrs不包含props中声明的属性,即使这些属性被传递给了子组件。
6. 示例对比
<script setup>
defineProps({
title: String,
});
const attrs = useAttrs();
console.log(attrs); // 输出 { id: "my-id", class: "my-class" }
</script>
<template>
<div>{{ title }} <!-- 只显示 title -->
<div v-bind="$attrs"> <!-- 绑定 id 和 class -->
Attrs Example
</div>
</div>
</template>
父组件:
<ChildComponent title="Hello" id="my-id" class="my-class" data-custom="value" />
title会显示在{{ title }}中。id和class会绑定到内部的<div>上。data-custom不会被绑定,除非显式处理。
总结来说,props 是组件接口的核心,用于定义子组件期望接收的数据,而 attrs 则用于处理未声明的属性或继承的属性。
注意
如果声明了props,attrs对象就没有该属性
前端工程师、程序员

浙公网安备 33010602011771号