// Vue 3 中的 attrs 示例
<template>
<div>
<!-- 将所有未被 props 捕获的 attribute 绑定到子组件上 -->
<child-component v-bind="$attrs"></child-component>
</div>
</template>
<script>
import { defineComponent } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default defineComponent({
name: 'ParentComponent',
components: {
ChildComponent,
},
inheritAttrs: false, // 禁用属性继承,防止未被 props 捕获的 attribute 被绑定到当前组件的根元素上
});
</script>
<!-- 子组件 -->
<template>
<div>
<!-- 使用 $attrs 获取所有未被 props 捕获的 attribute -->
<p>Attributes: {{ $attrs }}</p>
</div>
</template>
<script>
import { defineComponent } from 'vue';
export default defineComponent({
name: 'ChildComponent',
props: {
// 定义一些 props
message: String,
},
setup(props) {
console.log(props.message); // 访问传递给子组件的 message prop
console.log(this.$attrs); // 访问所有未被 props 捕获的 attribute
},
});
</script>
v-bind="$attrs":在父组件中使用 v-bind="$attrs" 可以将所有未被 props 捕获的 attribute 绑定到子组件上。这通常用于高阶组件或需要透传属性的场景。
inheritAttrs: false:默认情况下,Vue 会将所有未被 props 捕获的 attribute 绑定到当前组件的根元素上。通过设置 inheritAttrs: false,可以禁用这一行为,从而更好地控制这些 attribute 的去向。
$attrs:在子组件中,$attrs 是一个对象,包含了所有未被 props 捕获的 attribute。你可以通过 $attrs 来访问这些 attribute,并根据需要进行处理。
props:定义了 props 后,传递给子组件的属性会被自动捕获并赋值给 props,而未被 props 捕获的 attribute 则会存储在 $attrs 中。
希望这个示例能帮助你理解 Vue 3 中 attrs 的用法。
下一篇:vue父子组件传值props
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站