joken-前端工程师

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::

在 Vue 3 中,propsattrs 是两个不同的概念,它们的主要区别在于用途和行为。以下是它们的详细区别:


1. props

  • 定义props 是组件的自定义属性,用于从父组件向子组件传递数据。

  • 特点

    • props 是响应式的,父组件传递的数据变化会自动更新子组件中的 props
    • props 必须在子组件中显式声明(通过 definePropsprops 选项)。
    • props 是子组件的接口,用于定义子组件期望接收的数据。
    • props 不会包含继承的属性(如 classstyle),除非显式声明。
  • 示例

    <script setup>
    const props = defineProps({
      message: String,
    });
    </script>
    
    <template>
      <div>{{ message }}</div>
    </template>
    

    父组件传递 message

    <ChildComponent message="Hello, Vue 3!" />
    

2. attrs

  • 定义attrs 包含了所有传递给组件的非 props 属性,包括继承的属性(如 classstyle)以及未在 props 中声明的属性。

  • 特点

    • attrs 是非响应式的,它只是对 DOM 属性的直接映射。
    • attrs 包含了所有未在 props 中声明的属性,以及继承的属性(如 classstyle)。
    • 如果需要访问 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 会包含 idclassdata-custom


3. 主要区别

特性 props attrs
定义 显式声明的属性 非显式声明的属性
响应式
包含内容 自定义属性 props 属性和继承的属性
用途 组件接口,用于父子组件通信 处理未声明的属性或 DOM 属性
访问方式 definePropsprops 选项 useAttrs$attrs

4. 使用场景

  • props:当需要从父组件向子组件传递数据时使用,适合需要响应式更新的场景。
  • attrs:当需要处理未声明的属性或继承的属性时使用,适合需要直接操作 DOM 属性的场景。

5. 注意事项

  • 如果子组件没有声明 inheritAttrs: falseattrs 中的属性会自动绑定到根元素上。可以通过 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 }} 中。
  • idclass 会绑定到内部的 <div> 上。
  • data-custom 不会被绑定,除非显式处理。

总结来说,props 是组件接口的核心,用于定义子组件期望接收的数据,而 attrs 则用于处理未声明的属性或继承的属性。

注意

如果声明了props,attrs对象就没有该属性

posted on 2025-04-14 21:15  joken1310  阅读(276)  评论(0)    收藏  举报