📜  for i in range vue js - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:18.013000             🧑  作者: Mango

For Loop in Vue.js - JavaScript

In Vue.js, you can use the v-for directive to loop through an array or object and render each item. It's similar to using a for loop in JavaScript. Let's explore how to use it.

Syntax

The syntax for using v-for in Vue.js is as follows:

<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>

In this example, we are rendering a list of fruits using v-for. We are looping through the items array and rendering each item as an <li> element.

We are also using the key attribute with a unique identifier to optimize Vue's rendering process. It helps Vue track each item and update only the necessary changes when the array is modified.

Loop through an Object

You can also use v-for to loop through an object. The syntax is similar to looping through an array.

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

<script>
export default {
  data() {
    return {
      person: {
        name: 'John',
        age: 30,
        email: 'john@example.com'
      }
    }
  }
}
</script>

In this example, we are looping through the person object and rendering each property as a <li> element.

Loop through a Range

If you need to loop through a range of numbers in Vue.js, you can use the v-for directive with a range computed property.

<template>
  <div>
    <ul>
      <li v-for="n in range" :key="n">{{ n }}</li>
    </ul>
  </div>
</template>

<script>
export default {
  computed: {
    range() {
      return Array.from({ length: 10 }, (_, i) => i + 1)
    }
  }
}
</script>

In this example, we are creating a computed property range that generates an array of numbers from 1 to 10. We are then using v-for to loop through the array and render each number as an <li> element.

Conclusion

Using v-for in Vue.js is a powerful way to loop through arrays or objects and render each item dynamically. By using the key attribute and optimizing the rendering process, you can create performant and responsive applications.