最近在使用svg图标的时候,把svg图标单独作为了一个子组件并在父组件中引入使用后,直接在使用的图标上添加了一个class,结果报错Extraneous non-props attributes (class) were passed to component but could not be automatica。

  1. 子组件代码
<template>
        <svg>
           .... // 具体内容
        </svg>
</template>
  1. 父组件代码
import IconText from './icon/Text.vue'

<template>
	<div class="node-item">
    	<icon-text class="svg-node" />
	</div>
</template>
  1. 出现的问题
    经过上述代码的展示,最后在控制台报错Extraneous non-props attributes (class) were passed to component but could not be automatica
  2. 出现的原因
    icon-text 组件的模板中没有单一的根元素,或者它的根元素是一个 Fragment 或文本节点,这会导致传递的 class 等非 props 属性无法正确应用到组件的根元素上。
    正确使用方法为:(直接包含一层div)
<template>
    <div>
        <svg>
            ....
        </svg>
    </div>
</template>

Vue 组件的模板通常会有一个根元素,如 div、span 等标签。但是如果组件模板直接返回多个元素(使用 Fragment),或者返回的是一个文本节点,这些传递给组件的非 props 属性(如 class)就无法被应用到根元素,因为没有单一的根元素来接收它们。
Vue 支持将一些非 props 属性(比如 class、style 等)自动应用到组件的根元素上。这些属性通常称为“非 props 属性”或“attributes”。当组件的根元素为 Fragment 或文本节点时,这些属性就无法正常应用。

  1. 解决方案

(1)确保组件有一个单一的根元素

<template>
  <div class="component-root">
    <!-- 其他元素 -->
  </div>
</template>

(2)手动传递属性
如果确实需要使用 Fragment 或多个根元素,可以手动将传递的非 props 属性应用到你希望的元素上。你可以使用 $attrs 来获取这些属性,然后手动传递它们。

<template>
  <div v-bind="$attrs" class="component-root">
    <!-- 其他元素 -->
  </div>
</template>

此处举一个更加详细的例子来说明一下手动传递属性的用法。
父组件:

<template>
  <div>
    <MyComponent id="my-component" title="This is My Component" custom-attr="extra attribute"></MyComponent>
  </div>
</template>
<script>
import MyComponent from './MyComponent.vue';
export default {
  components: { MyComponent }
};
</script>

子组件:
通过 v-bind=“$attrs”,父组件传递过来的 id、title 和 custom-attr 将会直接绑定到

上。
其中inheritAttrs: false:禁止 Vue 将父组件的属性自动添加到组件的根元素上,可以手动控制属性的传递。

<template>
  <div v-bind="$attrs" class="component-root">
    <!-- 子组件的其他内容 -->
    <p>Hello from MyComponent</p>
  </div>
</template>
<script>
export default {
  inheritAttrs: false, // 禁用自动继承特性
};
</script>

<style scoped>
.component-root {
  border: 1px solid #ccc;
  padding: 10px;
}
</style>
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐