VueJS:无需声明props即可接收父组件任意属性并向下传递
解决方案:使用
$attrs和inheritAttrs实现属性透传 核心逻辑
当子组件未在props中声明对应属性时,父组件传入的属性会被Vue收集到$attrs对象中(而非$props)。配合inheritAttrs配置可以控制这些属性是否自动绑定到子组件根元素,同时通过v-bind="$attrs"就能把所有未知属性直接透传给下一级组件。
修改后的子组件代码
<template> <div> <p>I am {{ $attrs.name }} {{ $attrs.last_name }} and i am {{ $attrs.age }} old</p> <another-child v-bind="$attrs"></another-child> </div> </template> <script> import AnotherChild from "../another-child/another-child"; export default { components: { AnotherChild }, props: [], inheritAttrs: false, // 可选:若不想让属性自动绑定到当前子组件根元素,设置为false避免无效HTML属性 created() { console.log("未声明的属性集合", this.$attrs); // 输出结果:{name: 'John', last_name: 'Doe', age: '29'} } } </script>
关键细节说明
$attrs:包含父作用域中所有未被当前组件props识别的属性绑定(class和style除外),完全匹配你需要的未知属性集合。inheritAttrs: false:默认情况下Vue会把$attrs里的属性自动绑定到子组件的根DOM元素上。如果不需要这个行为(比如根元素是普通div,不需要多余自定义属性),就设置为false。- 多级透传:子组件用
v-bind="$attrs"传递属性后,孙组件可以直接声明对应props来使用,也可以继续用$attrs向下透传,直到目标组件接收使用。
内容的提问来源于stack exchange,提问作者Dipak Telangre
相关产品推荐
相关产品推荐

