vue中$attrs
时间: 2023-09-02 18:10:45 浏览: 120
在Vue中,$attrs是一个特殊的属性,它包含了父组件传递给子组件的非props属性。当一个子组件被创建时,父组件上的所有非props属性都会被自动添加到子组件的$attrs对象中。
$attrs对象是一个响应式的对象,它可以在子组件中使用。一般情况下,我们使用v-bind将$attrs对象中的属性绑定到子组件的根元素上,这样子组件就能接收到来自父组件的非props属性。
以下是一个示例:
父组件:
```
<template>
<child-component v-bind="$attrs"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
}
}
</script>
```
子组件:
```
<template>
<div>
<p>{{ $attrs.someAttr }}</p>
<p>{{ $attrs.anotherAttr }}</p>
</div>
</template>
```
在上面的示例中,父组件中的非props属性将通过v-bind指令绑定到子组件的根元素上,然后在子组件中可以通过$attrs对象访问到这些属性。
注意,$attrs只包含父组件传递给子组件的非props属性,并且在子组件内部无法修改$attrs对象。如果你需要在子组件中修改这些属性,可以使用$props对象来进行操作。
阅读全文
相关推荐

















