9951 explained code solutions for 126 technologies


vue.jsHow do I use the v-for directive in Vue.js?


The v-for directive is used in Vue.js to render a list of items based on an array. It works similarly to a for loop in JavaScript.

Example code

<div id="app">
  <ul>
    <li v-for="item in items">{{ item.text }}</li>
  </ul>
</div>

<script>
  new Vue({
    el: '#app',
    data: {
      items: [
        { text: 'Foo' },
        { text: 'Bar' },
        { text: 'Baz' }
      ]
    }
  })
</script>

Output example

Foo
Bar
Baz

The code consists of the following parts:

  1. <div id="app">: This is the root element for the Vue instance.
  2. <ul>: This is the unordered list element which will contain the items.
  3. <li v-for="item in items">: This is the directive which tells Vue to loop through the items array and create a list item for each item in the array.
  4. {{ item.text }}: This is the text that will be displayed for each list item.

Helpful links

Edit this code on GitHub