Vue报错:非props属性无法自动继承,已用根元素包裹组件
问题排查:Vue组件非Prop属性继承错误
错误提示
Extraneous non-props attributes were passed to component but couldn't be automatically inherited because component renders fragment or text root nodes
(翻译:传递给组件的额外非Prop属性无法自动继承,因为组件渲染的是多根节点片段或文本根节点)
问题原因
你误以为子组件有单个根元素,但实际上你的子组件(MainTopSection)的根是多个<section>元素——因为你把v-for直接写在了根<section>上,循环会生成多个同级的<section>,这就导致组件渲染的是多根节点片段,而非单个根元素。Vue的自动属性继承机制只在组件有单个根节点时生效,多根节点下Vue无法确定应该把非Prop属性继承到哪个节点,因此触发错误。
解决方案
方案1:添加单个根容器包裹
给子组件的循环元素套一个根容器,让组件只有一个根节点:
<template> <div> <!-- 新增根容器 --> <section v-for="item in jsonObject" :key="item"> <div :class="item.className"> <img :src="item.src" :alt="item.alt" :class="item.imgClassName"> <h2 v-html="item.h2Text"></h2> </div> </section> </div> </template> <script setup> import { defineProps } from "vue" const jsonObject = defineProps(['jsonObject']) </script>
方案2:显式绑定非Prop属性(无需额外根容器)
如果不想添加多余的根元素,可以用v-bind="$attrs"把非Prop属性手动绑定到目标节点上(比如每个循环的<section>):
<template> <section v-for="item in jsonObject" :key="item" v-bind="$attrs"> <div :class="item.className"> <img :src="item.src" :alt="item.alt" :class="item.imgClassName"> <h2 v-html="item.h2Text"></h2> </div> </section> </template> <script setup> import { defineProps } from "vue" const jsonObject = defineProps(['jsonObject']) </script>
方案3:禁用自动属性继承
如果组件不需要接收任何非Prop属性,可以直接关闭自动继承:
<template> <section v-for="item in jsonObject" :key="item"> <div :class="item.className"> <img :src="item.src" :alt="item.alt" :class="item.imgClassName"> <h2 v-html="item.h2Text"></h2> </div> </section> </template> <script setup> import { defineProps, defineOptions } from "vue" // 禁用属性自动继承 defineOptions({ inheritAttrs: false }) const jsonObject = defineProps(['jsonObject']) </script>
内容的提问来源于stack exchange,提问作者Harun Doğan
相关产品推荐
相关产品推荐

