$nextTick 是 Vue.js 中的一个方法,用于在下次 DOM 更新循环结束之后执行延迟回调。其原理是在当前 DOM 更新循环结束之后,将回调函数推入微任务队列中,等待下一个微任务执行时调用。这样可以确保在 DOM 更新完成后执行回调,以便获取更新后的 DOM 状态。
接下来我们用简单的例子来实现$nextTick的功能:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue2 $nextTick简单实现</title>
</head>
<body>
<div id="app"></div>
</body>
<script>
class Vue {
constructor(options) {
options.created.bind(this)();
this.$el = document.querySelector(options.el);
options.mounted.bind(this)();
}
$nextTick(callback) {
// Promise.resolve()是一个微任务,需要先执行constructor的宏任务再执行它
return Promise.resolve().then(() => {
callback();
})
}
}
new Vue({
el: '#app',
created() {
this.$nextTick(() => {
console.log('created nextTick:', this.$el); // created nextTick: <div id="app">vue2 $nextTick原理</div>
})
console.log('created:', this.$el); // created: undefined
},
mounted() {
console.log('mounted:', this.$el); // mounted: <div id="app">vue2 $nextTick原理</div>
}
});
</script>
</html>