gpt4 book ai didi

javascript - 如何正确迭代 Vue/Nuxt 中的对象数组

转载 作者:行者123 更新时间:2023-12-01 23:20:47 25 4
gpt4 key购买 nike

<template>
<div>
<h1>Hello World</h1>
<div>
<span :for="day in days">{{ day }} </span>
</div>
</div>
</template>

<script>
export default {
name: 'Hello',
data() {
return {
days: ['Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'],
}
},
}
</script>

我无法遍历 days 数组。我遇到了以下错误。

Error: [Vue warn]: Property or method "day" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

最佳答案

这是一个类似的问题:Nuxt how to loop on an array and display the data properly with a v-for

和那里一样,我建议生成一些 id 以正确处理 :key,否则你会收到 ESlint 错误。

<template>
<div>
<h1>Hello World</h1>
<div>
<span v-for="day in days" :key="day.id">
{{ day.name }}
</span>
</div>
</div>
</template>

<script>
export default {
name: 'Hello',
data() {
return {
days: [
{ id: 1, name: "Mon" },
{ id: 2, name: "Tue" },
{ id: 3, name: "Wed" },
{ id: 4, name: "Thurs" },
{ id: 5, name: "Fri" },
{ id: 6, name: "Sat" },
{ id: 7, name: "Sun" },
]
}
},
}
</script>

:key 是必不可少的,更多信息在这里:https://v2.vuejs.org/v2/style-guide/#Keyed-v-for-essential

这里有一篇博客文章对此进行了解释:https://michaelnthiessen.com/understanding-the-key-attribute#dont-use-an-index-as-the-key

关于javascript - 如何正确迭代 Vue/Nuxt 中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68115112/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com