拜托,我正在学习 VueJS 3,我可能有初学者问题。我在浏览器开发人员控制台中发出警告,如下所示:
消息是:
[Vue warn]: Extraneous non-props attributes (class) were passed to component but could not be automatically inherited because component renders fragment or text root nodes.
我将对象数组传递给子组件。在我的 parent views/Home.vue
我有这个实现:<template>
<div class="wrapper">
<section v-for="(item, index) in items" :key="index" class="box">
<ItemProperties class="infobox-item-properties" :info="item.properties" />
</section>
</div>
</template>
<script>
import { ref } from 'vue'
import { data } from '@/data.js'
import ItemProperties from '@/components/ItemProperties.vue'
export default {
components: {
ItemDescription,
},
setup() {
const items = ref(data)
return {
items,
}
},
</script>
在 child 评论 components/ItemProperties.vue
我有这个代码:<template>
<div class="infobox-item-property" v-for="(object, index) in info" :key="index">
<span class="infobox-item-title">{{ object.name }}:</span>
<span v-if="object.type === 'rating'">
<span v-for="(v, k) in object.value" :key="k">{{ object.icon }}</span>
</span>
<span v-else>
<span>{{ object.value }}</span>
</span>
</div>
</template>
<script>
export default {
props: {
info: {
type: Array,
required: false,
default: () => [
{
name: '',
value: '',
type: 'string',
icon: '',
},
],
},
},
}
</script>
如果我有 default()
没关系功能与否。如果我有 v-if
也没关系条件与否。如果我在数组中有循环,我会收到此警告数据在
data.js
文件。文件部分在这里:export const data = [
{
title: 'White shirt',
properties: [
{ name: 'Material', value: 'Cotton', type: 'string', icon: '' },
{ name: 'Size', value: 'M', type: 'string', icon: '' },
{ name: 'Count', value: 4, type: 'number', icon: '' },
{ name: 'Absorption', value: 4, type: 'rating', icon: '💧' },
{ name: 'Rating', value: 2, type: 'rating', icon: '⭐️' },
{ name: 'Confort', value: 2, type: 'rating', icon: '🛏' },
{ name: 'Sleeves', value: 'Short', type: 'string', icon: '' },
{ name: 'Color', value: 'White', type: 'string', icon: '' },
],
},
]
PS:应用程序有效,但我担心那个警告。我能做些什么请喜欢正确的方式?我会很高兴得到任何建议。非常感谢。
最佳答案
好吧,我认为错误信息很清楚。
您的 ItemProperties.vue
组件正在渲染片段 - 因为它正在渲染多个 <div>
使用 v-for
的元素.这意味着没有 单根元素。
同时,您正在传递一个 class
到带有 <ItemProperties class="infobox-item-properties"
的组件- class
只能放置在 HTML 元素上。如果将其放置在 Vue 组件上,Vue 会尝试将其放置在组件正在呈现的内容的根元素上。但是因为你的组件正在渲染的内容没有根元素,所以 Vue 不知道把它放在哪里......
要删除警告,请删除 class="infobox-item-properties"
或包装ItemProperties
的内容到单个 <div>
.
上述机制称为 Fallthrough Attributes (“非 Prop 属性”Vue 2 文档)。很高兴知道这个自动继承可以是switched off它允许您自己在根元素之外选择的元素(或组件)上应用这些属性。这可能非常有用。最值得注意的是,在围绕标准 HTML 元素(如输入或按钮)或某些库组件设计专门的包装器时......
关于javascript - Vue 3 传递数组警告 : Extraneous non-props attributes were passed to component but could not be automatically inherited,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68803137/