Home > Web Front-end > Vue.js > How to use v-cloak to solve flash problems in Vue

How to use v-cloak to solve flash problems in Vue

WBOY
Release: 2023-06-11 11:10:09
Original
1298 people have browsed it

Vue is a progressive framework for building user interfaces. More and more developers are beginning to use it to develop front-end interfaces in projects. In the process of using Vue, sometimes we will face some style flashing problems. This article will introduce how to use v-cloak in Vue to solve this problem.

What is the style flash problem?

When Vue renders a component, when Vue data binding is used in the template, the data is first parsed, and then the differences caused by the data changes are updated to the DOM. This process takes a certain amount of time, especially if the data is complex or there are many DOM nodes, it will cause a brief style change when the component is rendered when the page is loaded. This situation is called a style. Flash question.

The following two implementations are introduced respectively:

1. Using the display attribute of CSS

In the Vue component, you can set the display attribute to none through the style attribute, and then Modified to block during mounted() life cycle. After the Vue component is rendered, all CSS is loaded, which will cause the component's DOM to be hidden until it is first loaded.

<template>
  <div class="container" v-cloak>隐藏结果</div>
</template>
<style>
  [v-cloak] {
    display: none;
}
</style>
Copy after login
<script>
export default {
  mounted () {
    this.$nextTick(() => {
      this.show = true
    })
  }
}
</script>
Copy after login
Copy after login

This method is relatively simple and suitable for simple pages. But if the page is complex or needs to load some asynchronous data, this method may not be suitable. Then, you can consider using v-cloak to implement it.

2. Use v-cloak

v-cloak is one of the directives provided by Vue, which can be used to hide uncompiled Mustache syntax. The v-cloak element and its children will remain display:none until the Mustache syntax is parsed into an actual value. Once the Vue compiler is ready, the v-cloak elements will be removed.

<template>
  <div class="container" v-cloak>显示结果</div>
</template>
<style>
  [v-cloak] {
    display: none;
}
</style>
Copy after login
<script>
export default {
  mounted () {
    this.$nextTick(() => {
      this.show = true
    })
  }
}
</script>
Copy after login
Copy after login

Use the [v-cloak] directive on the component to control hiding, set the style through