07 使用v-for实现循环渲染

概述

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 属性对于正确增强反应性的重要性,那么我们将探讨如何在组件中使用、编写和触发方法。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/228004.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

代码随想录27期|Python|Day16|二叉树|104.二叉树的最大深度|111.二叉树的最小深度|222.完全二叉树的节点个数

二叉树专题&#xff0c;重点掌握后续的递归和中间节点的处理。 104. 二叉树的最大深度 - 力扣&#xff08;LeetCode&#xff09; 本题在前一章已经解决了层序遍历的解法&#xff0c;现在来聊一下递归法。 首先需要明确两个概念&#xff1a;深度和高度。&#xff08;注意&…

双向数据123

1. 原理 双向数据绑定的原理是使用数据劫持&#xff08;或者称为响应式&#xff09;和事件监听。当数据发生变化时&#xff0c;会触发视图的更新&#xff1b;同时&#xff0c;当用户与视图进行交互&#xff08;如在输入框中输入文字&#xff09;&#xff0c;变化会反映到数据模…

conda操作命令汇总

目录 conda命令&#xff1a;环境的创建与删除包&#xff08;第三方库&#xff09;的安装与卸载 参考链接 conda命令&#xff1a;环境的创建与删除 1.查看自己配置的环境 conda env list2.配置一个新的环境 conda create -n 环境的名字 python版本号3.进入和退出环境 activa…

抠图软件哪个好用?什么软件可以抠图换背景?

抠图软件哪个好用&#xff1f;在图片处理中&#xff0c;抠图换背景是一项常见的操作。很多新手可能会对此感到困惑&#xff0c;不知道应该使用什么软件来进行抠图换景。实际上&#xff0c;现在市面上有很多图片处理软件都具备抠图换背景的功能&#xff0c;每款软件都有其优缺点…

静态代理和动态代理的区别,什么场景使用

文章目录 静态代理和动态代理的区别&#xff0c;什么场景使用&#xff1f;静态代理&#xff1a;动态代理&#xff1a;实现步骤&#xff1a;使用场景&#xff1a; 静态代理和动态代理的区别&#xff0c;什么场景使用&#xff1f; 代理是一种常用的设计模式&#xff0c;目的是&a…

LVS负载均衡群集部署 DR模式

目录 DR模式直接路由 LVS-DR工作原理 LVS-DR 数据包流向分析 DR 模式的特点 DR模式 LVS负载均衡群集部署 DR模式直接路由 Direct Routing&#xff0c;简称DR模式&#xff0c;采用半开放式的网络结构&#xff0c;与TUN模式的结构类似&#xff0c;但各节点并不是分散在各地…

c语言链表的基本操作

在C语言中&#xff0c;链表是一种常见的数据结构&#xff0c;它由一系列节点组成&#xff0c;每个节点包含一个数据元素和一个指向下一个节点的指针。链表的基本操作包括创建、插入、删除和遍历等。 下面是一个简单的链表节点结构体定义&#xff1a; struct Node { int da…

Python实现员工管理系统(Django页面版 ) 六

本篇博客主要实现用户账号管理&#xff0c;这与之前的账号管理不同&#xff0c;之前的账号管理你可以理解为公司在外面买的一些手机号然后需要发放给员工做内部使用&#xff0c;而本篇博客的用户账号管理主要是为了后续的登录网页实现&#xff0c;那么我们开始今天的项目实现吧…

392. 判断子序列

双指针 class Solution {public boolean isSubsequence(String s, String t) {int i 0, j 0;while (i < s.length() && j < t.length()) {if (s.charAt(i) ! t.charAt(j)) {j;} else {i;j;}}if (i s.length()) return true;else return false;} }*有余力可以…

2. 套圈(分治)

题目 Have you ever played quoit in a playground? Quoit is a game in which flat rings are pitched at some toys, with all the toys encircled awarded. In the field of Cyberground, the position of each toy is fixed, and the ring is carefully designed so it c…

搭建消息时光机:深入探究RabbitMQ_recent_history_exchange在Spring Boot中的应用【RabbitMQ实战 二】

欢迎来到我的博客&#xff0c;代码的世界里&#xff0c;每一行都是一个故事 搭建消息时光机&#xff1a;深入探究RabbitMQ_recent_history_exchange在Spring Boot中的应用 引言前言第一&#xff1a;开启插件支持第二&#xff1a;springboot整合第三&#xff1a;效果展示交换机属…

locust 压测 websocket

* 安装 python 3.8 https://www.python.org/ py --version * 安装 locust pip install locust2.5.1 -i http://pypi.douban.com/simple/ pip install locust2.5.1 -i https://pypi.mirrors.ustc.edu.cn/simple/ locust -V 备注&#xff1a;-i 是切换下载源 * 安装依赖 pip ins…

Electron框架:构建跨平台桌面应用的终极解决方案

文章目录 一、Electron框架简介二、Electron框架的优势1. 开发效率高2. 跨平台性能好3. 易于维护4. 强大的原生能力 三、如何使用Electron框架快速开发跨平台桌面应用1. 安装Electron2. 创建项目文件夹3. 编写主进程代码4. 编写界面代码5. 运行应用 《Electron入门与实战》编辑…

《软件方法》2023版1.1利润=需求-设计1.2 ABCD工作流

DDD领域驱动设计批评文集 做强化自测题获得“软件方法建模师”称号 《软件方法》各章合集 第1章 建模和UML 牵着你走进傍晚的风里&#xff0c;看见万家灯火下面平凡的秘密。 《情歌唱晚》&#xff1b;词&#xff1a;黄群&#xff0c;曲&#xff1a;黄群&#xff0c;唱&#…

word文档实现“目录索引中标题加粗、前导符(...)和页码不加粗”效果

文章目录 1 展示论文模板需要呈现的效果2 所遇到的问题2.1 情形1&#xff1a;当更新整个目录后&#xff0c;目录中的所有文字都不加粗2.2 情形2&#xff1a;无法单独选中文字部分&#xff0c;如果相对文字部分加粗&#xff0c;则前导符和页码也会同时加粗 3 解决步骤3.1 步骤1&…

CIDR(无类域间路由)与VLSM(可变长度子网掩码)的区别

CIDR和VLSM的介绍 CIDR CIDR&#xff08;Classless Inter-Domain Routing&#xff0c;无类域间路由&#xff09;是一种用于对互联网协议&#xff08;IP&#xff09;地址进行聚合和分配的标准。CIDR的引入旨在解决IPv4地址空间的不足和低效分配的问题。在传统的IP地址规划中&a…

关键点检测之修改labelme标注的json中类别名

import json import os import shutil#source_dir表示数据扩增之后的文件夹路径&#xff0c;此时标注的是多分类的标签 #new_dir表示转化之后得到的二分类文件夹def to2class():#json存放路径source_dir r1#json保存路径new_dir r1for i in os.listdir(source_dir):if i.ends…

文本聚类——文本相似度(聚类算法基本概念)

一、文本相似度 1. 度量指标&#xff1a; 两个文本对象之间的相似度两个文本集合之间的相似度文本对象与集合之间的相似度 2. 样本间的相似度 基于距离的度量&#xff1a; 欧氏距离 曼哈顿距离 切比雪夫距离 闵可夫斯基距离 马氏距离 杰卡德距离 基于夹角余弦的度量 公式…

银行数字化转型导师坚鹏:银行数字化转型正在重塑您的工作

您好&#xff0c;我是银行数字化转型导师坚鹏。坚持知行果合一&#xff0c;赋能数字化转型&#xff01;非常荣幸和您分享关于银行数字化转型如何影响老百姓工作的一些思考。 您知道吗&#xff1f;银行数字化转型给您的工作方式带来新变化、新趋势、新潮流啦&#xff01;在这个…

Ubuntu 命令行安装 Clang 16或者Clang 17的过程

相关文章: How to install Clang 17 or 16 in Ubuntu 22.04 | 20.04 | UbuntuHandbook 在Ubuntu里面可以方便的用apt工具安装Clang 10, 11, 12, 13, 14 以及15。例如安装Clang 15只需要在Terminal中输入如下命令即可: sudo apt install clang-15 目前版本的Ubuntu如果想直接…