概述
To loop over HTML elements in Vue, you use the v-for loop directive directly on the target elements. When Vue renders the component, it will iterate the target to use and render the data being parsed into the directive, with the same concept as a normal JavaScript for loop.
要在 Vue 中对 HTML 元素进行循环,可以直接在目标元素上使用 v-for 循环指令。当 Vue 渲染组件时,它会遍历要使用的目标元素,并渲染解析到指令中的数据,其概念与普通 JavaScript for 循环相同。
v-for指令的基本用法
The basic syntax of v-for is as follows:
v-for 的基本语法如下:
v-for="(item, index) in items" :key="index"
The preceding syntax example indicates that we are iterating through a list of items. We have access to a single item and its appearance index in the list in each iteration. :key is a required attribute, acting as the unique identifier of each iterating element rendered for the Vue engine to keep track.
前面的语法示例表明我们正在迭代一个项目列表。在每次迭代中,我们都可以访问单个项目及其在列表中的外观索引。 :key 是一个必备属性,作为每个迭代元素的唯一标识符,供 Vue 引擎跟踪渲染。
When the key or item content changes, either programmatically or due to user interactions, the Vue engine triggers an update of the changed item on the UI. If you have multiple loops in one component, you should randomize the key attribute with extra characters or context-related strings to avoid key duplication conflicts.
当键值或项目内容发生变化时,无论是通过编程还是由于用户交互,Vue 引擎都会在用户界面上触发对变化项目的更新。如果一个组件中有多个循环,则应使用额外的字符或与上下文相关的字符串随机化键属性,以避免键重复冲突。
There are various use cases for this direction. One straightforward use case is to perform anonymous loops, in which you can define a number, X, as a symbolic list, and the loop will iterate that X times. This can be handy in situations in which you strictly control the number of iterations you want or render some placeholder content.
这个方向有多种用例。其中一个直接的用例是执行匿名循环,您可以将一个数字 X 定义为一个符号列表,然后循环将迭代 X 次。在严格控制迭代次数或呈现某些占位符内容的情况下,这将非常方便。
In the following example, we see an anonymous loop in which the total iterations are 2 and we define key with a loop-1 prefix:
在下面的示例中,我们看到了一个总迭代次数为 2 次的匿名循环,并定义了以 loop-1 为前缀的 key:
<template>
<div v-for="n in 2" :key="'loop-1-' + n">
{{ n }}
</div>
</template>
You can also use template literals (with `` backticks) to compute strings without +:
您还可以使用模板字面量(带 `` 反标)来计算不含 + 的字符串:
<template>
<div v-for="n in 5" :key="`loop-2-${n}`">
{{ n }}
</div>
</template>
Now that we have covered how to handle basic loops by using v-for, we will utilize this function in the next exercise.
现在,我们已经了解了如何使用 v-for 来处理基本循环,我们将在下一个练习中使用该函数。
练习:v-for遍历字符串数组
In this exercise, we are going to create an anonymous loop using Vue’s v-for directive. This will be familiar to those who have used for or forEach loops in JavaScript before.
在本练习中,我们将使用 Vue 的 v-for 指令创建一个匿名循环。以前在 JavaScript 中使用过 for 或 forEach 循环的用户对此不会陌生。
Create a new Vue component file named Exercise1-05.vue in the src/components directory.
在 src/components 目录中新建一个名为 Exercise1-05.vue 的 Vue 组件文件。
修改App.vue,引入该组件并渲染。
<script setup>
import Exercise from "./components/Exercise1-05.vue";
</script>
<template>
<Exercise/>
</template>
Inside Exercise1-05.vue, we compose a new component with an <h1>
element to render the static title of Looping through arrays, and an<ul>
element containing an empty<li>
tag:
在 Exercise1-05.vue 中,我们用一个 <h1>
元素和一个包含空 <li>
标记的 <ul>
元素组成一个新组件,<h1>
元素用于呈现静态标题 "通过数组循环":
<template>
<h1>Looping through arrays</h1>
<ul>
<li></li>
</ul>
</template>
In the script section, let’s add a setup attribute to the script tag. Then, let’s declare an array of interests containing some strings as follows:
在脚本部分,让我们为脚本标记添加一个设置属性。然后,让我们声明一个包含一些字符串的兴趣数组,如下所示:
<script setup>
const interests = ['TV', 'Games', 'Sports']
</script>
Now, let’s go back to the template section and add the v-for directive on the <li>
tag to iterate through interests. For each iteration, we get a combination of (item, index) from the interests, in which item outputs the string of the array, and index is the loop index.
现在,让我们回到模板部分,在 <li>
标记上添加 v-for 指令,以遍历兴趣点。每次迭代,我们都会从兴趣中获取一个(item、index)组合,其中 item 输出数组的字符串,index 是循环索引。
We map the key attribute to index, and display the value of item as shown in the following code block:
我们将 key 属性映射到索引,并显示 item 的值,如下代码块所示:
<template>
<h1>Looping through arrays</h1>
<ul>
<li v-for="(item, index) in interests"
:key="index">{{ item }}</li>
</ul>
</template>
In this exercise, we learned how to iterate through a specific array of strings, outputting the string value or index of an array. We also learned that the key attribute needs to be unique to avoid DOM conflicts and forces the DOM to re-render the component properly.
在本练习中,我们学习了如何遍历特定字符串数组,输出字符串值或数组索引。我们还学习了 key 属性必须是唯一的,以避免 DOM 冲突,并强制 DOM 正确地重新渲染组件。
Next, let’s experiment with iterating a collection of objects.
接下来,让我们尝试迭代对象集合。
v-for遍历对象数组
In most practical scenarios, we work with data as objects, especially when iterating through an array of objects. Vue makes it easy to control various data states through its directive syntax. Like iterating through an array of strings, the directive syntax remains the same:
在大多数实际场景中,我们以对象的形式处理数据,尤其是在迭代对象数组时。Vue 可通过其指令语法轻松控制各种数据状态。与迭代字符串数组一样,指令语法保持不变:
v-for="(item, index) in items" :key="index"
The item you receive is now an Object, with various properties. You can bind each property using what you have learned so far to display its value. For example, assume in item, we will have id, title, description, and another array, characteristics, containing some strings. We can display the title and description information for each item like so:
现在,您收到的项目是一个对象,具有各种属性。您可以使用迄今所学的知识绑定每个属性,以显示其值。例如,假设 item 中有 id、title、description 和另一个包含字符串的数组 characteristics。我们可以这样显示每个项目的标题和描述信息:
<template>
<ul>
<li v-for="(item, index) in items" :key="item.id">
<h2>{{ item.title }}</h2>
<span>{{ item.description }}</span>
</li>
</ul>
</template>
Note here we don’t use an index as the key; instead, we use id as the unique identifier for key. It is considered a more secure approach to use id or any other unique identifier and we also don’t need to include index in the syntax in this case since we don’t use it.
请注意,这里我们没有使用索引作为键,而是使用 id 作为键的唯一标识符。使用 id 或其他唯一标识符被认为是一种更安全的方法,在这种情况下,我们也不需要在语法中包含索引,因为我们没有使用它。
Since characteristics is an array, we display its values by using a v-for directive again for characteristics. You don’t have to use the same name, item, that the syntax example shows. Instead, you can give it a different name depending on how you want your variable to be.
由于 characteristics 是一个数组,因此我们再次使用 v-for 指令来显示其值。您不必使用与语法示例中相同的名称 item。相反,你可以根据你对变量的要求给它起一个不同的名字。
In the following example, we use str for each element in the item.characteristics array:
在下面的示例中,我们对 item.characteristics 数组中的每个元素都使用了 str:
<template>
<ul>
<li v-for="item in items" :key="item.id">
<h2>{{ item.title }}</h2>
<span>{{ item.description }}</span>
<ul>
<li v-for="(str, index) in item.characteristics"
:key="index">
<span>{{ str }}</span>
</li>
</ul>
</li>
</ul>
</template>
And in the script section, we define items as follows:
在脚本部分,我们定义项目如下:
<script setup>
const items = [{
id: 1,
title: "Item 1",
description: "About item 1",
characteristics: ["Summer", "Winter", "Spring", "Autumn"]
}, {
id: 2,
title: "Item 2",
description: "About item 2",
characteristics: ["North", "West", "East", "South"]
}]
</script>
Understanding how to loop through collections of objects with v-for is essential and useful for handling data, especially with external data. In the next exercise, you will combine v-for and v-if to display a list of objects conditionally.
了解如何使用 v-for 循环对象集合对于处理数据(尤其是外部数据)非常重要和有用。在下一个练习中,您将结合 v-for 和 v-if,有条件地显示对象列表。
练习:根据条件渲染对象列表
In this exercise, we will be controlling a Vue data array and iterating through the objects inside of it.
在本练习中,我们将控制一个 Vue 数据数组并遍历其中的对象。
Create a new Vue component file named Exercise1-06.vue in the src/components directory.
在 src/components 目录中新建一个名为 Exercise1-06.vue 的 Vue 组件文件。
修改App.vue,引入并渲染该组件:
<script setup>
import Exercise from "./components/Exercise1-06.vue";
</script>
<template>
<Exercise/>
</template>
Inside Exercise1-06.vue, create an array of data objects, interests, as local data. Each interest contains a title string and a favorites array of strings:
在 Exercise1-06.vue 中,创建一个数据对象数组,即兴趣,作为本地数据。每个兴趣包含一个标题字符串和一个收藏字符串数组:
<script setup>
const interests = [
{
title: "TV",
favorites: ["Designated Survivor", "Spongebob"],
},
{
title: "Games",
favorites: ["CS:GO"],
},
{
title: "Sports",
favorites: [],
},
];
</script>
In template, we loop over interests and display the title for each item in the interests array:
在模板中,我们循环查看兴趣,并显示兴趣数组中每个项目的标题:
<template>
<div>
<h1>Looping through array of objects</h1>
<ul>
<li v-for="(item, n) in interests" :key="n">
{{ item.title }}
</li>
</ul>
</div>
</template>
Let’s create a second v-for loop to iterate through a favorites list for each item. Note that we use different names – fav and m – for our nested loop:
让我们创建第二个 v-for 循环,遍历收藏夹列表中的每个条目。请注意,我们为嵌套循环使用了不同的名称--fav 和 m:
<template>
<div>
<h1>Looping through array of objects</h1>
<ul>
<li v-for="(item, n) in interests" :key="n">
{{ item.title }}
<ol>
<li v-for="(fav, m) in item.favorites"
:key="m">
{{ fav }}
</li>
</ol>
</li>
</ul>
</div>
</template>
Now, we need to hide that empty <ol>
element after applying it. We will check whether the favorites array is empty (length > 0) and then display the ordered list HTML element.
现在,我们需要在应用后隐藏空的 <ol>
元素。我们将检查收藏夹数组是否为空(长度 > 0),然后显示有序列表 HTML 元素。
Let’s add a v-if directive to <ol>
with the item.favorites.length > 0 condition:
让我们为 <ol>
添加一个 v-if 指令,条件是 item.favorites.length > 0:
<ol v-if="item.favorites.length > 0">
<li v-for="(fav, m) in item.favorites" :key="m">
{{ fav }}
</li>
</ol>
This won’t make a difference to the visuals of your page, but when you inspect the DOM tree in your browser, you’ll notice an HTML comment in dev mode that allows you to understand where a v-if statement might be false. When you build for production, these HTML comments won’t be visible in your DOM tree.
这不会对页面的视觉效果造成影响,但当您在浏览器中检查 DOM 树时,您会发现在开发模式下有一个 HTML 注释,它可以让您了解 v-if 语句在哪些地方可能是假的。当您为生产构建时,DOM 树中就看不到这些 HTML 注释了。
In this exercise, we have iterated through complex arrays of objects, outputting the nested keys for these objects and controlling the view state of DOM elements based on length conditions.
在本练习中,我们遍历了复杂的对象数组,输出了这些对象的嵌套键,并根据长度条件控制了 DOM 元素的视图状态。
Next, let’s experiment with iterating through a keyed collection (or Object).
接下来,让我们尝试迭代带键集合(或对象)。
v-for遍历对象
We can generally use v-for for looping through any iterative data collection type. Object in JavaScript is a key-value data collection, and we can iterate through its properties using v-for.
一般来说,我们可以使用 v-for 遍历任何迭代数据集合类型。JavaScript 中的 Object 是键值数据集,我们可以使用 v-for 遍历其属性。
The syntax example is like the previous syntax example for arrays of objects and strings, with a tiny difference. Here, we change the naming convention from (item, index) to (value, key), in which key is the object’s property, and value is that key property’s value. Vue also exposes one more parameter – index – to indicate that property’s appearance index in the target object. Thus, the syntax now becomes the following:
该语法示例与之前的对象数组和字符串数组语法示例类似,但有细微差别。在这里,我们将命名约定从(item, index)改为(value, key),其中 key 是对象的属性,value 是该 key 属性的值。Vue 还多了一个参数--index,用于表示该属性在目标对象中的外观索引。因此,现在的语法如下:
v-for="(value, key, index) in obj"
Here, obj is our target object to iterate.
这里,obj 是我们要遍历的目标对象。
For example, assume we have the following object named course, which contains a title, a description, and the name of the lecturer(s):
例如,假设我们有以下名为课程的对象,其中包含标题、描述和讲师姓名:
<script setup>
const course = {
title: 'Frontend development with Vue',
description: 'Learn the awesome of Vue',
lecturer: 'Maya and Raymond'
}
</script>
In our template, we iterate through the course’s properties and output their value in the <index>
.< key > : <value>
format as shown in the following code block:
在我们的模板中,我们遍历课程的属性,并以 <index>
.< key >
: <value>
的格式输出它们的值,如以下代码块所示:
<template>
<ul>
<li v-for="(value, key, index) in course" :key="key">
{{index}}. {{key}}: {{value}}
</li>
</ul>
</template>
Looping through the properties of an object is also a joint development practice. It is the same concept as winding through any keyed collection type, such as a hash-map (mapping according to key), lookup dictionary (it is also an object), and so on. Since the syntax stays consistent between both array and object iteration, it helps reduce the need for refactoring or data conversion.
循环查看对象的属性也是一种联合开发实践。这与循环浏览任何带键集合类型(如散列表(根据键映射)、查找字典(也是对象)等)的概念相同。由于数组和对象迭代的语法保持一致,因此有助于减少重构或数据转换的需要。
Next, you will practice how to write basic looping for Object properties.
接下来,您将练习如何编写对象属性的基本循环。
练习:遍历对象
In this exercise, we will be controlling a Vue data object and iterating through the properties inside of it.
在本练习中,我们将控制一个 Vue 数据对象并遍历其中的属性。
Create a new Vue component file named Exercise1-07.vue in the src/components directory.
在 src/components 目录中新建一个名为 Exercise1-07.vue 的 Vue 组件文件。
修改App.vue,引入该组件并渲染:
<script setup>
import Exercise from "./components/Exercise1-07.vue";
</script>
<template>
<Exercise/>
</template>
Inside Exercise1-07.vue, let’s compose information for the local data within <script setup>
as follows:
在 Exercise1-07.vue 中,让我们在 <script setup>
中编写本地数据信息,如下所示:
<script setup>
const information = {
title: "My list component information",
subtitle: "Vue JS basics",
items: ["Looping", "Data", "Methods"],
}
</script>
In the <template>
section, we will loop through information and display the values of its properties:
在<template>
部分,我们将循环浏览信息并显示其属性值:
<template>
<div>
<div v-for="(value, key) in information" :key="key">
{{ key }}: {{ value }}
</div>
</div>
</template>
Note that Vue renders the value for items, which is an array of strings, the same as how we declared using JavaScript. To render it in a better format, we use the built-in JavaScript toString() function to export all the elements’ values into a string with comma separation automatically:
请注意,Vue 为 items 显示的值是一个字符串数组,与我们使用 JavaScript 声明的值相同。为了以更好的格式呈现,我们使用内置的 JavaScript toString() 函数将所有元素的值自动导出为以逗号分隔的字符串:
<template>
<div>
<div v-for="(value, key) in information" :key="key">
{{key}}: {{ value.toString() }}
</div>
</div>
</template>
总结
Understanding iterations (or loops) is key to not only working with Vue but also with JavaScript in general. Now that we have covered how to handle loops by using the v-for directive and the importance of the key property for proper reactivity enhancement, we will explore how to use, write, and trigger methods in a component.
了解迭代(或循环)不仅是使用 Vue 的关键,也是一般 JavaScript 的关键。既然我们已经介绍了如何使用 v-for 指令来处理循环,以及 key 属性对于正确增强反应性的重要性,那么我们将探讨如何在组件中使用、编写和触发方法。