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
React vs. Vue: Which Framework Does Netflix Use?React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

The Choice of Frameworks: What Drives Netflix's Decisions?The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AM

Netflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.

React, Vue, and the Future of Netflix's FrontendReact, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AM

Netflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.

Vue.js in the Frontend: Real-World Applications and ExamplesVue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AM

Vue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.

Vue.js and React: Understanding the Key DifferencesVue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AM

Vue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.

Vue.js vs. React: Project-Specific ConsiderationsVue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AM

Vue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.

How to jump a tag to vueHow to jump a tag to vueApr 08, 2025 am 09:24 AM

The methods to implement the jump of a tag in Vue include: using the a tag in the HTML template to specify the href attribute. Use the router-link component of Vue routing. Use this.$router.push() method in JavaScript. Parameters can be passed through the query parameter and routes are configured in the router options for dynamic jumps.

How to implement component jump for vueHow to implement component jump for vueApr 08, 2025 am 09:21 AM

There are the following methods to implement component jump in Vue: use router-link and <router-view> components to perform hyperlink jump, and specify the :to attribute as the target path. Use the <router-view> component directly to display the currently routed rendered components. Use the router.push() and router.replace() methods for programmatic navigation. The former saves history and the latter replaces the current route without leaving records.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft