学习优先度:★★★★☆

难易度:★★★★☆

Vue 的 v-for 指令可以遍历数组和对象,为呈现列表和键值对提供了灵活性。

下面的示例演示了 v-for 在数组和对象中的应用:

【代码示例】

<template>
  <div>
  <h2>Array Example:</h2>
  <ul>
   <li v-for="(fruit, index) in fruits" :key="index">
     {{ index }}: {{ fruit }}
   </li>
  </ul>
text<h2>Object Example:</h2>
<ul>
 <li v-for="(value, key) in person" :key="key">
  {{ key }}: {{ value }}
 </li>
</ul>
 </div>
</template>
<script>
export default {
 data() {
  return {
   fruits: ['Apple', 'Banana', 'Cherry'],
   person: {
     name: 'John Doe',
     age: 30,
     job: 'Developer'
   }
  }
 }
}
</script>

【执行结果】

Array Example:
• 0: Apple
• 1: Banana
• 2: Cherry
Object Example:
• name: John Doe
• age: 30
• job: Developer

Vue.js 中的 v-for 指令用途广泛,既可用于数组,也可用于对象。这种灵活性允许开发人员轻松遍历不同的数据结构。

对于数组:

语法是 v-for="(item, index) in array"

item 表示数组中的每个元素

index 是当前索引(可选)

对于对象:

语法是 v-for="(value, key, index) in object"

value 是对象的属性值

key 是属性名称

index 是迭代索引(可选)

在这两种情况下,我们都使用 :key 为每个呈现的元素提供唯一标识符。对于数组,我们使用索引作为键(当然,如果有的话,最好使用唯一标识符)。对于对象,我们使用属性名称(键)作为唯一标识符。

无论是处理数组还是对象,这种方法都能让 Vue 在数据发生变化时高效地更新 DOM。

【补充】

  • Vue 3 引入了对一系列数字使用 v-for 的功能,例如,v-for=“n in 5"可以将一个元素重复 5 次。

  • 在对对象使用 v-for 时,顺序基于 Object.keys(),但这并不能保证在不同 JavaScript 引擎中保持一致。

  • 在 v-for 中使用时,Vue 会自动解开 ref,因此在模板中访问 ref 值时无需使用 .value。