import Vue from 'vue'; export default { setup(props, context) { console.log(Vue.version); return {}; } };
When we change the responsive state
, the Vue
updateDOM
is not updated synchronously in real time, but all state updates executed synchronously are cached and the synchronous code is After the execution is completed, perform the Dom update operation, which greatly optimizes render
performance and reduces the number of Dom
updates;
And this feature brings One problem is that we cannot get the real Dom
after state
is changed, so Vue provides nextTick
to get the updated state
Dom
function nextTick(callback?: () => void): Promise<void>
Use case
<template> <div class="test_demo"> <h3 class="text">{{ text }}</h3> <button @click="onBtnClick">更新</button> </div> </template> <script lang="ts" setup> import { ref, nextTick } from 'vue'; const text = ref('test_0'); const onBtnClick = () => { text.value = 'test_1'; nextTick(() => { const text = ( document.querySelector<HTMLElement>('.text') as HTMLElement ).innerText; console.log(text); }); text.value = 'test_2'; }; </script>
After clicking the Update
button, output test_2. However, if text.value = 'test_1';
is commented out, the output result is quite different, test_0 is output.
Why is there this problem?
text.value
The assignment operation is synchronous and real-time. When the code execution encounters a responsive state
change, a view update logic## will be submitted. #Go to the microtask queue, and when nextTick is encountered, it will also be submitted to the microtask queue. So in the above code,
View update logic is in front of
nextTick,
View update logic is executed by changing
text.value = 'test_1' and
text.value = 'test_2'Update the view after merging, so output test2;
text.value = 'test_1',
nextTick The order in the microtask queue is in front of
View update logic, so test_0 is output.