如何在 v-for 中绑定源属性

huangapple go评论57阅读模式
英文:

how to bind on a source property in v-for

问题

在给定的这个教程中

如下所示的代码,我尝试迭代items数组并在运行时显示item.message
我收到以下错误消息:

在迭代中的元素期望有'v-bind:key'指令 vue/require-v-for-key

请告诉我如何在v-for中绑定到源属性

代码:

<template>
  <li v-for="item in items">
	{{ item.message }}
  </li>
</template>

<script>

export default {
  name: 'App',
}
</script>

<script setup>
import {ref} from 'vue' 

const items = ref([{ message: 'Foo' }, { message: 'Bar' }])

</script>
英文:

given this tutorial

as shown below in the code, i am trying to iterate through items array and display item.message
at run time, i receive the following error:

Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key

please let me know how can i bind on source property in v-for

code:

<template>
  <li v-for="item in items">
	{{ item.message }}
  </li>
</template>

<script>

export default {
  name: 'App',
}
</script>

<script setup>
import {ref} from 'vue' 

const items = ref([{ message: 'Foo' }, { message: 'Bar' }])

</script>

答案1

得分: 1

在Vue文档中了解:key的信息:
https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key
为了方便,始终为v-for提供:key,通过在列表中的对象中选择某个唯一值,在您的情况下似乎是message,因为您没有任何id属性:

<template>
  <li v-for="item in items" :key="item.message">
    {{ item.message }}
  </li>
</template>
英文:

Read about :key in the Vue docs:
https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key
To make your life easier just always provide :key for v-for by selecting some unique value in your objects in the list, in your case it seems message since you don't have any id property:

&lt;template&gt;
  &lt;li v-for=&quot;item in items&quot; :key=&quot;item.message&quot;&gt;
    {{ item.message }}
  &lt;/li&gt;
&lt;/template&gt;

huangapple
  • 本文由 发表于 2023年5月17日 18:25:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76271087.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定