可以先看下 深入响应式原理 - vue.js 这个官方文档,如果看不懂再来看这些博客。
Vue 实现响应式并不是数据发生变化之后 DOM 立即变化,而是按一定的策略进行 DOM 的更新。
$nextTick 是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后使用 $nextTick,则可以在回调中获取更新后的 DOM,API 文档中官方示例如下:
new Vue({
// ...
methods: {
// ...
example: function () {
// modify data
this.message = 'changed'
// DOM is not updated yet
this.$nextTick(function () {
// DOM is now updated
// `this` is bound to the current instance
this.doSomethingElse()
})
}
}
})
比如当改变msg1中的值时,就会执行回调,获取更改之后的值。
new Vue({
el: '.app',
data: {
msg1: '',
},
watch: { //不能用es6语法就用这个方法 msg1:function(){ this.$nextTick(function () { console.log(this.msg1); }); }, //这是es6语法箭头函数,在没有引入es6语法的项目中就不可以使用。 this.$nextTick(() => { this.msg2 = this.$refs.msgDiv.innerHTML }) }, }, })