Home > Article > Web Front-end > Prevent vuejs from flickering during parsing
---## Prevent vuejs from flickering during parsing ##
Reason:
When developing using vuejs and angularjs, we often encounter expressions ({{ express }}) or module (div) flickering on browsers such as Chrome that can quickly parse. For this problem, JavaScript will wait for DOM loading to complete (DOM ready) when operating DOM. For vuejs and angularjs, they will go back to parse the html view template after the DOM is ready, so for fast browsers such as Chrome, you will see flickering. For browsers such as IE7 and 8 that have slightly slower parsing, this problem will not occur in most cases.
Solution:
In vuejs and angularjs, we provide v-cloak and ng-cloak to prevent flickering. At the same time, for bing text ({{ express }}), we can also change it to v-bind, ng -bind to avoid this.
The following takes vuejs as an example:
<code>#v-cloak 用法: 这个指令保持在元素上直到关联实例结束编译。和 CSS 规则如 [v-cloak] { display: none } 一起用时,这个指令可以隐藏未编译的 Mustache 标签直到实例准备完毕。 示例:</code>
<span style="color: #008080;">1</span> <span style="color: #800000;">[v-cloak] </span>{ <span style="color: #008080;">2</span> <span style="color: #ff0000;"> display</span>:<span style="color: #0000ff;"> none</span>; <span style="color: #008080;">3</span> } <span style="color: #008080;">4</span> <span style="color: #008080;">5</span> <span style="color: #800000;"><div v-cloak> </span><span style="color: #008080;">6</span> {<span style="color: #ff0000;">{ message </span>}<span style="color: #800000;">} </span><span style="color: #008080;">7</span> <span style="color: #800000;"></div></span>
<code><div> 不会显示,直到编译结束。 原理: 带有v-clock的的元素设置为display:none,隐藏掉,在等到vue解析到带有v-clock的节点时候,会把attribute和class同时remove掉,这样就可以实现防止节点的闪烁。 实例:</code>
<span style="color: #000000;">//example1: </span><span style="color: #0000ff;"><</span><span style="color: #800000;">span</span><span style="color: #0000ff;">></span>{{price}}<span style="color: #0000ff;"></</span><span style="color: #800000;">span</span><span style="color: #0000ff;">></span><span style="color: #000000;"> //example2: </span><span style="color: #0000ff;"><</span><span style="color: #800000;">span </span><span style="color: #ff0000;">v-bind</span><span style="color: #0000ff;">="price"</span><span style="color: #0000ff;">></</span><span style="color: #800000;">span</span><span style="color: #0000ff;">></span><span style="color: #000000;"> //example3: </span><span style="color: #0000ff;"><</span><span style="color: #800000;">span </span><span style="color: #ff0000;">v-cloak</span><span style="color: #0000ff;">></span>{{price}}<span style="color: #0000ff;"></</span><span style="color: #800000;">span</span><span style="color: #0000ff;">></span>
<code> 上例子2和例子3实现的效果是一样的,而例子1在vuejs解析{{price}}之前,用户是可以看到"{{price}}"这个字符串的。而例子2和例子3不会有这种闪烁的情况。</code>