vue3使用$nextTick
在vue3中使用nextTick很简单,如下:
<script setup>
import { ref, nextTick } from 'vue'
// 这里也可以使用reactive
const userInfo = ref({})
const updateUser = async () => {
userInfo.name = '张三'
userInfo.age = 13
await nextTick()
// dom已经更新
// do something
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
使用很简单但我们还是有必要了解nextTick的原理,最快的方式自然是读源码啦:在目录/runtime-core/scheduler.ts中可以看到实现的方式
nextTick中创建了一个微任务,利用js的事件循环机制让回调在下一次渲染之后运行
const resolvedPromise: Promise<any> = Promise.resolve()
let currentFlushPromise: Promise<void> | null = null
export function nextTick(
this: ComponentPublicInstance | void,
fn?: () => void
): Promise<void> {
const p = currentFlushPromise || resolvedPromise
return fn ? p.then(this ? fn.bind(this) : fn) : p
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
那什么是事件循环呢?可以参考以下资料: 事件循环:微任务与宏任务 浏览器事件循环机制的动态演示-视频
上次更新: 2025/09/05, 8:09:00