Home > Web Front-end > Vue.js > How to use v-for to iterate arrays or objects in Vue

How to use v-for to iterate arrays or objects in Vue

WBOY
Release: 2023-06-11 10:34:37
Original
1297 people have browsed it

Vue.js is a flexible JavaScript framework that allows developers to build interactive web applications more easily. In Vue, we can use the v-for directive to iterate over an array or object and generate the corresponding HTML elements.

Array iteration

In Vue.js, we can use the v-for directive to iterate an array. Here is a simple example:

<template>
  <div>
    <ul>
      <li v-for="(item, index) in items" :key="index">
        {{ item }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ["apple", "banana", "orange"],
    };
  },
};
</script>
Copy after login

In the above example, the v-for instruction iterates over the items array. The item and index in the instruction represent each element in the array and its subscript in the array respectively. Note: To avoid duplicate warnings, we need to specify a unique key using the :key attribute (in this case, we use the array index as the key).

Object iteration

In addition to iterating arrays, Vue.js also allows us to iterate objects. Here is a simple example:

<template>
  <div>
    <ul>
      <li v-for="(value, key) in object" :key="key">
        {{ key }}: {{ value }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  data() {
    return {
      object: {
        name: "Tom",
        age: 18,
        hobby: "swimming",
      },
    };
  },
};
</script>
Copy after login

In the above example, the v-for instruction iterates the object object. The value and key in the instruction represent each value and its corresponding key in the object respectively. As with array iteration, we need to specify a unique key using :key (in this case, we use the key in the object as the key).

Summary

Vue.js’s v-for directive makes iterating over arrays or objects easier. Whether when iterating over an array or an object, we need to specify a unique key using :key to avoid duplication.

I hope this article is helpful to you, and happy coding!

The above is the detailed content of How to use v-for to iterate arrays or objects in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template