inheritAttrs: false 是 Vue 2.4.0+ 引入的组件选项,用于控制是否从父组件继承属性到子组件的根元素上。当设置为 true 时(默认行为),父组件中的非 prop 属性会被应用到子组件的根元素上。当设置为 false 时,这些属性不会被应用到子组件的根元素上。
例如,如果你有以下父组件:
| <template> | |
|   <div> | |
|     <child-component class="parent-class" id="parent-id" /> | |
|   </div> | |
| </template> | |
| <script> | |
| import ChildComponent from './ChildComponent.vue'; | |
| export default { | |
|   components: { | |
| ChildComponent | |
| } | |
| } | |
| </script> | 
而子组件是这样的:
| <template> | |
| <div>子组件内容</div> | |
| </template> | |
| <script> | |
| export default { | |
| inheritAttrs: false | |
| } | |
| </script> | 
当 inheritAttrs: false 时,子组件的根元素上不会有 class="parent-class" 和 id="parent-id" 属性。
如果你需要在子组件中使用这些属性,你应该显式地通过 props 传递它们:
| <template> | |
| <div :class="classAttr" :id="idAttr">子组件内容</div> | |
| </template> | |
| <script> | |
| export default { | |
| props: ['classAttr', 'idAttr'], | |
| inheritAttrs: false | |
| } | |
| </script> | 
父组件需要更新,将对应的属性通过 props 传递给子组件:
| <template> | |
|   <div> | |
|     <child-component :class-attr="'parent-class'" :id-attr="'parent-id'" /> | |
|   </div> | |
| </template> | |
| <script> | |
| import ChildComponent from './ChildComponent.vue'; | |
| export default { | |
|   components: { | |
| ChildComponent | |
| } | |
| } | |
| </script> | 
这样,子组件就能够接收并使用父组件传递过来的属性了。
