search
HomeWeb Front-endVue.jsA practical introduction to Vue.js: How to loop over arrays and objects

A practical introduction to Vue.js: How to loop over arrays and objects

In the previous section (Course Part 3) we learned how to use v-if and v -show Perform conditional rendering. In this section we will learn how to loop over arrays and objects, in addition to applying some of the concepts we learned previously.

v-for

v-for is one of the basic instructions of Vue. Once you learn how to use it, you can Add more features to the program.

Simply put, v-for is a for loop. If you still don’t know what a for loop is, a for loop is actually a piece of code. Each element in the code will be executed once, and these elements are usually an Array (Array) or Object(Object).

Today, we’re going to start from the beginning so that everything we do has a clear purpose. Below is the basic structure of our index.html file, which you can copy and paste into your editor.



  <title>Vue 101</title>



  <div>

  </div>

  <script></script>

  <script>
    const app = new Vue({
      el: &#39;#app&#39;,
      data: {

      },
      methods: {

      }
    });
  </script>


Let's create a simple array first so that we can use a loop to output the contents of the array. We will create a property in the data object called games. Of course, you can also choose a name you like???.

data: {
  games: [
    'Super Mario 64',
    'The Legend of Zelda Ocarina of Time',
    'Secret of Mana',
    'Super Metroid'
  ]
},

Now that we have the array set up, let's create a simple <ul></ul> tag to display it.

<div id="app">
  <ul>
    <li>Game title here</li>
  </ul>
</div>

Looks great! Now we need to tell Vue that we want to output as many <li> as possible in <ul></ul> by looping through the array Label.

In other languages, you may have been accustomed to looping the output like this<li> Tag:

<?php foreach ($game in $games): ?>
  <li><?php echo $game; ?></li>
<?php endforeach; ?>

Will need to loop the output<li> tags are wrapped in a loop.

But in Vue, we can declare the v-for directive on the label we want to loop. First make the following changes in your <li> tag, and then we will analyze it step by step.

<ul>
  <li v-for="game in games">{{ game }}</li>
</ul>

Let us analyze it in detail:

    <li>

    v-for The command is added directly to <li> tag instead of the <ul></ul> tag we saw earlier. The reason for writing this is: "Create a <li> tag for each game in our games array.

    <li>

    Note that games is the attribute we added earlier in data, so we have to use this variable name.

    <li>

    game This variable (singular) is defined by ourselves. We can use item, game, title or anything else we think is appropriate. name. But you must understand that this game is the variable you want to use in the loop.

    <li>

    Finally, in our <li> In the tag, we want to output the contents of the game variable, so when we run the loop, the strings in the games array will be output to &lt ;li> tag.

Open our index.html file in your browser, you should see games The contents of the array are output to the screen.

Increase the difficulty

So far, so good, right? v-for It's actually a very simple concept, but this example is too boring. Let's make things a little more complicated and interesting by including some objects in our array and using v-if, How's that?

First, let's update our games properties with some more interesting data.

data: {
  games: [
    { name: &#39;Super Mario 64&#39;, console: &#39;Nintendo 64&#39;, rating: 4 },
    { name: &#39;The Legend of Zelda Ocarina of Time&#39;, console: &#39;Nintendo 64&#39;, rating: 5 },
    { name: &#39;Secret of Mana&#39;, console: &#39;Super Nintendo&#39;, rating: 4 },
    { name: &#39;Fallout 76&#39;, console: &#39;Multiple&#39;, rating: 1 },
    { name: &#39;Super Metroid&#39;, console: &#39;Super Nintendo&#39;, rating: 6 }
  ]
},

If you run our program now, it won't go wrong , but it will only output the objects in games in string format, which is not pretty. In fact, we have to completely delete our <ul></ul> tag and use

tag to output our information. (Don’t worry, it will still look ugly if you use div?)

Replace the entire

Replace with the following content:
<div id="app">
  <div v-for="game in games">
    <h1 id="nbsp-game-name-nbsp-nbsp-nbsp-small-nbsp-game-console-nbsp-small">{{ game.name }} - <small>{{ game.console }}</small></h1>

    <span v-for="star in game.rating">❤️</span>

    <div v-if="game.rating > 5">Wow, this game must be <b>REALLY</b> good</div>
  </div>
</div>

?. Are you scared to see a lot of the above? Don’t worry, you just need to know what it is, let us analyze it in detail:

    <li>

    div v-for="game in games" Still the same, we need to loop the games array and convert the games array Each object within is stored in a game variable.

    <li>

    看看 <h1></h1> 标签. 因为 game 是一个对象,而这个对象里又有自己的 nameconsolerating 属性。在 <h1></h1> 里面,我们要输出 game 内的 game.namegame.console。正如你现在所看到的那样,v-for 并不像我们之前只输出 <li> 标签,实际上你可以根据你的需要输出不同的 HTML 标签。

    <li>

    嵌套的 v-for。在 span 标签里面,我们有一个嵌套的 v-for 循环(这完全是可以的),只是有点不同,在这里我们没有循环数组或对象。而是循环了一个数值(在本例中是 game.rating,循环将根据 game.rating 的值开始计数,然后输出对应数量的❤️。很简单吧?)

    <li>

    最后是 v-if。我们要在循环中输出一个 <div> 标签,只有当前 <code>game.rating 的值大于 5 时,才会输出一个<div>标签。<p>来吧,在浏览器中继续运行我们的 <code>index.html 文件。

    每次循环时可不可以不使用 DIV ?

    如果你发现写了一大堆 <div> 标签只是为了用 <code>v-for 循环,那么可以使用 <template> template></template> 这个特殊的 HTML 标签帮助你解决这个问题。

    现在将带有 v-for 指令的 <div> 标签改成 <code><template></template> 标签,然后打开你的开发者控制台,你会发现 <h1></h1><span></span> 标签没有被任何东西包裹。

    <template></template> 很特别,因为 Vue 会把它当作一个只用来封装的标签,当我们执行的时候,它不会被渲染到 HTML 中,所以你可以安全地用它来封装一堆其他元素,而不影响你整体的 HTML 结构。

    :key 属性

    最后一件事::key属性。我特意留到了最后来讲解。

    当你用 v-for 循环时,Vue 不知道如何追踪每个元素,因为它不能将对象区别开来。这意味着 Vue 将重新渲染循环创建的整个部分。在我们的例子中,v-for 只是一个很小的部分,性能损失很小,但这些你应该牢记住。

    现在,我们该如何使用它呢?

    :key 接收字符串或数字来 “命名” 或 “追踪” 这个元素,所以我们需要给它一个唯一的标识符。对于我们的 games 来说,很简单,我们可以这样做:

    <div v-for="game in games" :key="game.name">

    我很确定,我们不会在这个列表中出现两次相同的 game 对象,所以这是相当安全的。如果你有来自数据库的数据,一个唯一的 id 在这里使用也很好。

    如果你对 :key 的原理很好奇,你可以看看文档 Key的文档

    既然你已经了解了这么多,我就再强调下文档的重要性。 Vue 的文档非常出色,文档团队在保持更新和清晰性方面做了很多努力并且通过代码示例把每个部分都解释的非常清楚。

    最终代码

    以防万一,这是最终的代码:

    
    
    
      Vue 101
    
    
    
    
    <div v-for="game in games" :key="game.name">

    {{ game.name }} - {{ game.console }}

    ❤️
    Wow, this game must be REALLY good
<script> const app = new Vue({ el: &#39;#app&#39;, data: { games: [ { name: &#39;Super Mario 64&#39;, console: &#39;Nintendo 64&#39;, rating: 4 }, { name: &#39;The Legend of Zelda Ocarina of Time&#39;, console: &#39;Nintendo 64&#39;, rating: 5 }, { name: &#39;Secret of Mana&#39;, console: &#39;Super Nintendo&#39;, rating: 4 }, { name: &#39;Fallout 76&#39;, console: &#39;Multiple&#39;, rating: 1 }, { name: &#39;Super Metroid&#39;, console: &#39;Super Nintendo&#39;, rating: 6 } ] } }); </script>

小测验

请在 <span></span> 标签中添加一个 @click 事件,使它每次点击就会增加一个❤️。

提示: 你需要将正在循环的 game 对象传递给点击方法。

原文地址:https://dev.to/marinamosti/hands-on-vuejs-for-beginners-part-4-324l

译文地址:https://www.php.cn/link/5a13fe4ac11f3e35f4b9f0a99cf504c0

(学习视频分享:web前端开发编程基础视频

The above is the detailed content of A practical introduction to Vue.js: How to loop over arrays and objects. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:learnku. If there is any infringement, please contact admin@php.cn delete
What Happens When the Vue.js Virtual DOM Detects a Change?What Happens When the Vue.js Virtual DOM Detects a Change?May 14, 2025 am 12:12 AM

WhentheVue.jsVirtualDOMdetectsachange,itupdatestheVirtualDOM,diffsit,andappliesminimalchangestotherealDOM.ThisprocessensureshighperformancebyavoidingunnecessaryDOMmanipulations.

How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?How Accurate Is It to Think of Vue.js's Virtual DOM as a Mirror of the Real DOM?May 13, 2025 pm 04:05 PM

Vue.js' VirtualDOM is both a mirror of the real DOM, and not exactly. 1. Create and update: Vue.js creates a VirtualDOM tree based on component definitions, and updates VirtualDOM first when the state changes. 2. Differences and patching: Comparison of old and new VirtualDOMs through diff operations, and apply only the minimum changes to the real DOM. 3. Efficiency: VirtualDOM allows batch updates, reduces direct DOM operations, and optimizes the rendering process. VirtualDOM is a strategic tool for Vue.js to optimize UI updates.

Vue.js vs. React: Scalability and MaintainabilityVue.js vs. React: Scalability and MaintainabilityMay 10, 2025 am 12:24 AM

Vue.js and React each have their own advantages in scalability and maintainability. 1) Vue.js is easy to use and is suitable for small projects. The Composition API improves the maintainability of large projects. 2) React is suitable for large and complex projects, with Hooks and virtual DOM improving performance and maintainability, but the learning curve is steeper.

The Future of Vue.js and React: Trends and PredictionsThe Future of Vue.js and React: Trends and PredictionsMay 09, 2025 am 12:12 AM

The future trends and forecasts of Vue.js and React are: 1) Vue.js will be widely used in enterprise-level applications and have made breakthroughs in server-side rendering and static site generation; 2) React will innovate in server components and data acquisition, and further optimize the concurrency model.

Netflix's Frontend: A Deep Dive into Its Technology StackNetflix's Frontend: A Deep Dive into Its Technology StackMay 08, 2025 am 12:11 AM

Netflix's front-end technology stack is mainly based on React and Redux. 1.React is used to build high-performance single-page applications, and improves code reusability and maintenance through component development. 2. Redux is used for state management to ensure that state changes are predictable and traceable. 3. The toolchain includes Webpack, Babel, Jest and Enzyme to ensure code quality and performance. 4. Performance optimization is achieved through code segmentation, lazy loading and server-side rendering to improve user experience.

Vue.js and the Frontend: Building Interactive User InterfacesVue.js and the Frontend: Building Interactive User InterfacesMay 06, 2025 am 12:02 AM

Vue.js is a progressive framework suitable for building highly interactive user interfaces. Its core functions include responsive systems, component development and routing management. 1) The responsive system realizes data monitoring through Object.defineProperty or Proxy, and automatically updates the interface. 2) Component development allows the interface to be split into reusable modules. 3) VueRouter supports single-page applications to improve user experience.

What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools