Vue 3 v-cloak Directive
v-cloak The directive is used to hide uncompiled templates until the component instance is ready.
Basic Explanation
v-cloak The directive solves the "uncompiled template flash" problem when using DOM templates. When the user visits the page, they may see the raw {{ }} mustache tags, until the Vue component mounts and renders content.
v-cloak remains on the element until the associated component instance finishes mounting. Combined with CSS rules, the raw template can be hidden during this period.
- Expected type: none (does not accept an expression)
- Purpose: hide the uncompiled template until the component is ready.
Note: This directive is only needed in setups without a build step.
Basic Usage
When using v-cloak , you need to pair it with CSS rules:
Example
/* CSS rule: hide elements with v-cloak */
[
v-cloak
]
{
display
:
none
;
}
Example
{{ message }}
When compilation is complete,v-cloak the attribute is automatically removed from the element, and the element is then displayed.
Use Cases
v-cloak Mainly used in the following scenarios:
1. Using a CDN to include Vue
When Vue is included via CDN without a build step, the template may not yet be compiled during the brief time between page load and the Vue script.
Example
{{ message }}
2. Complex template structures
For complex templates with multiple data bindings, v-cloak prevents users from seeing unrendered content:
Example
{{ title }}
Welcome, {{ username }}
-
{{ item.name }}
How v-cloak Works
- When the page loads, Vue is not yet initialized, and the
v-cloakattribute exists on the element - CSS rules
[v-cloak] { display: none; }hide these elements - Vue initializes and compiles the template, creating reactive data
- After the component mounts, Vue automatically removes
v-cloakproperty - and the element displays, showing the rendered content
Notes
Only for scenarios without a build step: When using build tools (such as Vite, Webpack), the template is already compiled at build time, so v-cloak is not needed.
Example
/* ensure the v-cloak rule loads before all other styles */
/* it is recommended to place CSS in the head */
Must be used with CSS: v-cloak itself does not hide content; it must be paired with CSS rules to take effect.
Difference from Modern Build Tools
When using modern build tools (such as Vite), you do not need v-cloak, because:
- The template is pre-compiled at build time
- JavaScript is inlined or loaded asynchronously after bundling
- The initial HTML does not contain uncompiled template syntax
Therefore, v-cloak is mainly used for the traditional CDN inclusion approach or simple HTML page scenarios.
Vue 3 Built-in Directives