Categories
JavaScript Vue

Using a For Loop with Vuejs

Spread the love

We can render lists by using a for loop with Vuejs.

The for loop equivalent in Vuejs is the v-for directive.

To use it, we can write;

<ul id="example">
  <li v-for="item in items" :key="item.name ">
    {{ item.name }}
  </li>
</ul>

and:

const example = new Vue({
  el: '#example',
  data: {
    items: [
      { name: 'Foo' },
      { name: 'Bar' }
    ]
  }
})

We have an items array with the list items to render

Then we use v-for with the items array to render them items.

We need the key prop with a unique value for each entry for Vuejs to identify the entries properly.

We can also add the index by changing our v-for for loop.

For instance, we can write:

<ul id="example">
  <li v-for="(item, index) in items">
    {{ index }} - {{ item.name }}
  </li>
</ul>

and:

const example = new Vue({
  el: '#example',
  data: {
    parentMessage: 'Parent',
    items: [
      { name: 'Foo' },
      { name: 'Bar' }
    ]
  }
})

index has the index of the array.

We can also loop through objects.

For instance, we can write:

<ul id="v-for-object">
  <li v-for="value in object">
    {{ value }}
  </li>
</ul>

and

new Vue({
  el: '#v-for-object',
  data: {
    object: {
      name: 'james'.
      age: 20,
      gender: 'male'
    }
  }
})

We loop through the keys of the object in our Vuejs app with the same for loop.

value has the property value.

We can also add the property name and index to the loop.

For instance, we can write:

<div v-for="(value, name) in object">
  {{ name }}: {{ value }}
</div>

value is the property value and name is the property name.

We can also add the index to our Vuejs for loop by writing:

<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>

We can create a Vuejs for loop that display numbers by writing a number after the in instead of an array or object.

For instance, we can write:

<div>
  <span v-for="n in 100">{{ n }} </span>
</div>

We can v-for with a `template component to render multiple items.

For instance, we can write:

<ul>
  <template v-for="item in items">
    <li>{{ item.msg }}</li>
    <li><hr /></li>
  </template>
</ul>

to render multiple items in each iteration of the v-for Vuejs for loop.

The Vuejs equivalent of a for loop is the v-for directive.

We can use it to render objects and array entries on the screen.

Also, we can use it to loop through a range of numbers and display them.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.