More Vue Directives

Now that we have covered the basics of the Vue directives, now we will cover some more directives that can help improve the user experience of our web applications.

v-show

The v-show directive can be used as an alternative to v-if. Their usage is nearly the same, but how they are rendered is different.

<div id="app">
  <button @click="show = !show">Toggle</button>
  <p v-show="show">Hello</p>
</div>
const app = new Vue({
  el: '#app',
  data: {
    show: false
  }
})

The main difference between v-if and v-show is that the v-show will always be rendered, but will have a style="display: none" attribute added when its expression is false. The v-show directive is preferred if the element will be toggled often.

v-html

The v-html directive is used in place of the mustache syntax when an HTML string needs to be displayed.

NOTE

Mustache syntax cannot be used to display raw HTML as it will be displayed as a string.

<div id="app">
  <p>{{ html }}</p>
  <p v-html="html"></p>
</div>
const app = new Vue({
  el: '#app',
  data: {
    html: '<strong style="color: #c00">Hello</strong>'
  }
})

v-cloak

The v-cloak directive, when combined with CSS, is used to "hide" elements that are still being processed by Vue. This will prevent an un-compiled mustache binding from being displayed on the page. The v-cloak directive takes no expression and will be removed once the element has been compiled.

<div id="app" v-cloak>
  <h1>{{ title }}</h1>
  <p>{{ message }}<p>
</div>
[v-cloak] > * {
  display: none;
}

[v-cloak]::before {
  content: 'Loading...';
  margin: 1rem;
}