Conditional Rendering in Vue with v-if

Jul 4, 2019

The v-if directive allows you to conditionally render a block. It differs from v-show in that v-if doesn't actually create the element if its expression evaluates to false.

const app = new Vue({
  data: () => ({ render: false }),
  template: `
    <div>
      <h1 v-if="render">Hello, World</h1>
    </div>
  `
});

// Vue will **not** render 'Hello, World' because the `v-if`
// expression evaluates to false.
const data = await renderToString(app);
// <div data-server-rendered="true"><!----></div>
data;

v-else-if and v-else

Vue also has v-else-if and v-else directives that behave like else if and else in JavaScript.

const app = new Vue({
  data: () => ({ value: 1 }),
  template: `
    <div>
      <div v-if="value > 0">Positive</div>
      <div v-else-if="value < 0">Negative</div>
      <div v-else>Zero</div>
    </div>
  `
});

let data = await renderToString(app);
// <div data-server-rendered="true"><div>Positive</div></div>
data;

app._data.value = -1;
data = await renderToString(app);
// <div data-server-rendered="true"><div>Negative</div></div>
data;

app._data.value = 0;
data = await renderToString(app);
// <div data-server-rendered="true"><div>Zero</div></div>
data;

Lifecycle Hooks

Vue components have lifecycle hooks, like the created hook that gets called when the component gets created, and mounted when the component gets mounted.

When Vue renders a component because the v-if expression became truthy, it triggers both the 'created' and 'mounted' hooks. For example, the below code will print both 'Created!' and 'Mounted!' every time display changes to true from false.

Vue.component('test', {
  created: function() {
    console.log('Created!');
  },
  mounted: function() {
    console.log('Mounted!');
  },
  template: '<h1>Hello World</h1>'
});

const app = new Vue({
  data: () => ({ display: false }),
  template: `
    <div id="rendered-content">
      <test v-if="display"></test>
      <div>
        <button v-on:click="display = !display">Toggle</button>
      </div>
    </div>
  `
});

Vue School has some of our favorite Vue video courses. Their Vue.js Master Class walks you through building a real world application, and does a great job of teaching you how to integrate Vue with Firebase. Check it out!


Did you find this tutorial useful? Say thanks by starring our repo on GitHub!

More Vue Tutorials