Conditionals and Loops

Conditional Rendering

The v-if directive is used to conditionally render a block. The block will only be rendered if the directive's expression returns a truthy value. The v-else directive can be added, which will be rendered if the expression of the previous v-if returns falsy.

<div id="app">
  <div v-if="name">
    Hello, {{ name }}
  </div>
  <div v-else>
    Hello, Friend
  </div>
</div>
const app = new Vue({
  el: '#app',
  data: {
    name: 'Michael'
  }
})

Loops

The v-for directive can be used to repeatedly render a template block.

Iterating over Arrays and Objects

The v-for directive will render a block for every data item in an array or object. For iterating over an array or object, v-for directive using the following syntax as it's value: item in collection, where collection is the array or object and item is the current element.

<ul id="list">
  <li v-for="item in items">
    {{ item }}
  </li>
</ul>
const list = new Vue({
  el: '#list',
  data: {
    items: ['Milk', 'Eggs', 'Bread']
  }
})

Repeatedly Render

If you need repeatedly render a block, without an array or object, the v-for can be used to repeat a template block a specified number of times, as in the example below.

<ul id="app">
  <p v-for="i in 3">Hip Hip Hurray!</p>
</ul>