How will nextTick be used in the project?
Defer the callback until after the next DOM update cycle. Use it immediately after you have changed some data to wait for DOM updates
.'<div>{{ message }}</div>'.import { createApp, nextTick } from "vue";
const app = createApp({
setup() {
const message = ref("Hello!");
const changeMessage = async(newMessage) => { message.value! [](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3d736591f5f949f9a6d74c027743e0f1~tplv-k3u1fbpfcp-watermark.image) = newMessage;
await nextTick();
console.log("Now DOM is updated");
};
return{ message, }; }});Copy the code
The principle of nextTick
The browser only renders once at the end of a taskThe eventloop of the browser is shown below:
As shown in the figure, the execution sequence is microTask > UI Render > macroTask
NextTick gets the updated DOM. Using setTimeout(function) can achieve the effect of nextTick. The problem with setTimeout implementation nextTick, however, is that the minimum interval between setTimeouts is about 4ms, which imposes a minimum time difference between two renders.
Vue’s nextTick is implemented through Promise(microTask) : because of the virtual DOM, the same effect can be achieved even before the UI renders, without limiting the twice rendering time
In the source code after Vue2.5, Vue nextTick’s downgrading strategy is: microTask(Promise) > macroTask(setImmediate) > macroTask(MessageChannel) > macroTask(setTimeout)
Simulate nextTick implementation
setTimeout(f)
SetTimeout (f) also has a broader use: shred CPU-intensive tasks.
For example, if you have a task that counts from 1 to 100000000, it is very likely that if you execute a for loop or a while loop directly, it will say: the current page is not responding.
let i = 0;
let start = Date.now();
function count() {
// do a piece of the heavy job (*)
do {
i++;
} while (i % 1e6! =0);
if (i == 1e9) {
alert("Done in " + (Date.now() - start) + "ms");
} else {
setTimeout(count); // schedule the new call (**)
}
}
count();
Copy the code
Reference:
- Event loop: microtasks and macrotasks
- Comprehensive analysis of vue. nextTick implementation principle