Vue2-$props与$attrs属性

247 阅读1分钟

在 Vue 2 中,$props$attrs 是用于访问组件属性和非 props 特性的两个属性。

  • $props: 包含父组件传递给当前组件特性(attributes)中已被 props 声明的特性。在子组件中,可以通过 $props 访问和获取这些值。
  • $attrs:包含所有没有被 props 声明的特性。这些特性会继续传递给子组件的根元素,除非子组件明确声明将其绑定到其他元素,通常在开发高级组件时使用。
<!-- ParentComponent.vue -->
<template>
  <ChildComponent attr1="attr1 from parent" attr2="attr2 from parent" />
</template>

<!-- ChildComponent.vue -->
<template>
  <div>
    <p>已接收的 Attributes: {{ props.attr1 }}</p>
    <p v-bind="$attrs">未接收的 Attributes: {{ $attrs.attr2 }}</p>
  </div>
</template>

<script>
export default {
  props: ["attr1"],
  mounted() {
    console.log(this.$props.attr1);
    // 输出:attr1 from parent
    console.log(this.$props.attr2);
    // 输出:undefined

    console.log(this.$attrs.attr1);
    // 输出:undefined
    console.log(this.$attrs.attr2);
    // 输出:attr2 from parent
  },
};
</script>

Tips:v-bind="$props"v-bind="$attrs"

  • v-bind="$props":将父组件中所有 props 传递给子组件。子组件需要在 props:{} 中定义要接收的 props
  • v-bind="$attrs":将调用组件时的组件标签上绑定的非 props 的特性(排除 class 和 style)向下传递给子组件。在子组件中,需要设置 inheritAttrs: false,以避免父作用域的特性绑定被应用在子组件的根元素上。