坚持就是胜利。胜利不重要,重要的是能坚持人生最大的哀痛,是子欲孝而亲不在!人生最大的悲剧,是家未富而人先亡,人生最大的可怜,是弥留之际才明白自己是应该做什么的!
1 nextTick的使用
vue中dom的更像并不是实时的,当数据改变后,vue会把渲染watcher添加到异步队列,异步执行,同步代码执行完成后再统一修改dom,我们看下面的代码。
<template>
<div class="box">{{msg}}</div>
</template>
export default {
name: 'index',
data () {
return {
msg: 'hello'
}
},
mounted () {
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
console.log(box.innerHTML) // hello
}
}
可以看到,修改数据后并不会立即更新dom ,dom的更新是异步的,无法通过同步代码获取,需要使用nextTick,在下一次事件循环中获取。
this.msg = 'world'
let box = document.getElementsByClassName('box')[0]
this.$nextTick(() => {
console.log(box.innerHTML) // world
})
如果我们需要获取数据更新后的dom信息,比如动态获取宽高、位置信息等,需要使用nextTick。
2 数据变化dom更新与nextTick的原理分析
2.1 数据变化
vue双向数据绑定依赖于ES5的Object.defineProperty,在数据初始化的时候,通过Object.defineProperty为每一个属性创建getter与setter,把数据变成响应式数据。对属性值进行修改操作时,如this.msg = world,实际上会触发setter。下面看源码,为方便越读,源码有删减。
双向数据绑定
数据改变触发set函数
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// 数据修改后触发set函数 经过一系列操作 完成dom更新
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
dep.notify() // 执行dep notify方法
}
})
执行dep.notify方法
export default class Dep {
constructor () {
this.id = uid++
this.subs = []
}
notify () {
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
// 实际上遍历执行了subs数组中元素的update方法
subs[i].update()
}
}
}
当数据被引用时,如<div>{{msg}}</div> ,会执行get方法,并向subs数组中添加渲染Watcher,当数据被改变时执行Watcher的update方法执行数据更新。
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
queueWatcher(this) //执行queueWatcher
}
}
update 方法最终执行queueWatcher
function queueWatcher (watcher: Watcher) {
const id = watcher.id
if (has[id] == null) {
has[id] = true
if (!flushing) {
queue.push(watcher)
} else {
// if already flushing, splice the watcher based on its id
// if already past its id, it will be run next immediately.
let i = queue.length - 1
while (i > index && queue[i].id > watcher.id) {
i--
}
queue.splice(i + 1, 0, watcher)
}
// queue the flush
if (!waiting) {
// 通过waiting 保证nextTick只执行一次
waiting = true
// 最终queueWatcher 方法会把flushSchedulerQueue 传入到nextTick中执行
nextTick(fl