在 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,以避免父作用域的特性绑定被应用在子组件的根元素上。