0
0
VueHow-ToBeginner · 3 min read

How to Use v-cloak in Vue for Smooth Content Rendering

Use the v-cloak directive on an element to hide it until Vue finishes compiling the template. Combine it with CSS to keep the element hidden initially and reveal it once Vue is ready, preventing flickering of raw template syntax.
📐

Syntax

The v-cloak directive is added as an attribute to an HTML element. It works with CSS to hide the element until Vue finishes compiling the template inside it.

Example parts:

  • v-cloak: The directive placed on the element.
  • CSS rule [v-cloak] { display: none; }: Hides the element initially.
  • Vue removes the v-cloak attribute after compilation, making the element visible.
html
<div id="app" v-cloak>
  {{ message }}
</div>

<style>
[v-cloak] {
  display: none;
}
</style>
Output
The div is hidden until Vue compiles and replaces {{ message }} with actual text, then it becomes visible.
💻

Example

This example shows how v-cloak hides the raw template text until Vue finishes rendering the message.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Vue v-cloak Example</title>
  <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
  <style>
    [v-cloak] {
      display: none;
    }
  </style>
</head>
<body>
  <div id="app" v-cloak>
    <p>{{ message }}</p>
  </div>

  <script>
    Vue.createApp({
      data() {
        return {
          message: 'Hello, Vue with v-cloak!'
        };
      }
    }).mount('#app');
  </script>
</body>
</html>
Output
Hello, Vue with v-cloak!
⚠️

Common Pitfalls

  • Not adding the CSS rule [v-cloak] { display: none; } means the raw template will show briefly.
  • Placing v-cloak on a parent element but styling only child elements can cause flicker.
  • Using v-cloak without Vue mounting the app properly will keep the element hidden forever.
vue
<!-- Wrong: Missing CSS hides nothing -->
<div id="app" v-cloak>
  {{ message }}
</div>

<!-- Right: Add CSS to hide until compiled -->
<style>
[v-cloak] {
  display: none;
}
</style>
📊

Quick Reference

v-cloak usage tips:

  • Always include the CSS rule [v-cloak] { display: none; }.
  • Use v-cloak on the root element of your Vue app or on elements with template syntax.
  • Vue automatically removes the v-cloak attribute after compilation.
  • Helps prevent flicker of raw mustache syntax before Vue renders.

Key Takeaways

Use v-cloak with CSS to hide uncompiled Vue templates and prevent flicker.
Always add the CSS rule [v-cloak] { display: none; } to hide elements initially.
Vue removes the v-cloak attribute automatically after rendering.
Place v-cloak on elements containing Vue template syntax for best effect.
Without proper CSS, v-cloak will not hide raw template content.