官方文档的解释:
在下次 DOM 更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的 DOM。
虽然 Vue.js 鼓励开发人员沿着“数据驱动”的方式思考,避免直接接触 DOM,但是有时我们确实要这么做。
比如在Vue生命周期的created()钩子函数进行的DOM操作一定要放在Vue.nextTick()的回调函数中。原因是什么呢,原因是在created()钩子函数执行的时候DOM 其实并未进行任何渲染,而此时进行DOM操作无异于徒劳,所以此处一定要将DOM操作的js代码放进Vue.nextTick()的回调函数中。
<template>
<div>
<span>{{ message }}</span>
<button @click="updateMessage">点我</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "not updated"
};
},
created() {},
methods: {
updateMessage: function() {
this.message = "updated";
console.log(this.$el.textContent); // => 'not updated'
this.$nextTick(function() {
console.log(this.$el.textContent); // => 'updated'
});
}
}
};
</script>