this.$nextTick()
- vue中的数据更新是异步的,也就是修改Vue实例data中的数据之后,不能立刻获得修改后的dom元素(要等到真实dom更新之后)
- vue在dom更新之后会回调this.nextTick(),通过this.nextTick(),通过this.nextTick(),通过this.nextTick()可以获取到更新之后的dom元素
DOM更新
- vue在内存中维护了一个虚拟dom,数据变化时vue会检测到这种变化,然后创建一个新的虚拟dom树木,用新树和旧树对比差异,找到最小更新量再一次性更新到真实dom上。
例子
将vue响应式数据data中的某个变量绑定到某个元素中<span ref="test">{{ name }}</span>
当我们改变name然后马上查看dom
this.name = 'new'
console.log(this.$refs.test.innerHTML)
可以看到打印的值是改变之前的,因为dom更新是异步的。
可以在更新之后的回调中打印
this.$nextTick(() => { console.log(this.$refs.test.innerHTML) })
这样看到的才是更新后的dom