Vue.js v-cloak | Removing Mustache Flicker

Explains how to remove mustache expression flicker in Vue.js.

What Is v-cloak?

Let us look at VueJS’s v-cloak directive.

v-cloak, used in VueJS, is a built-in directive that hides content in the browser before VueJS renders it. Here, “hide” is different from the role of v-if or v-show, which hide and show content conditionally.

To understand the difference, first look at how Vue.js works.

  1. The browser loads the page source.
  2. The VueJS framework runs.
  3. VueJS processing completes.

During this process, before Vue.js has finished processing, expressions such as {{ }} or content that should not be shown through v-if can appear on the screen as-is. This only happens for a very brief moment before Vue.js rendering, but it is an unavoidable process. To avoid it, use v-cloak.

Implementation with VueJS v-cloak

When v-cloak is applied to an element, VueJS automatically removes the v-cloak directive after processing is complete. In other words, the v-cloak attribute is removed from the tag. If you specify the CSS property display: none; so that elements with v-cloak are not exposed on screen, the element will not be shown to users until Vue.js processing is complete.

First, for the implementation, specify display: none so that an element with v-cloak is hidden.

[v-cloak] {
  display: none;
}

Then add the v-cloak directive to the tag where it should be applied.

<div v-cloak>
    Hello, {{ name }}
</div>

With this, when VueJS has completed processing all DOM elements, v-cloak automatically disappears and the elements it was applied to are displayed on the screen.

Replacing the Display with a Loading Message Using v-cloak

We have seen that v-cloak automatically disappears after loading. There is also another way to use it as a loading message. If you apply the following CSS style, the pseudo-selector ::before prints the text “Loading”, and all following elements are hidden.

[v-cloak]::before {
  content: 'Loading...'
}

[v-cloak] > * {
  display:none;
}

Reference