<template>
<div id="container">
<h1>苹果{{ message }}</h1>
<button @click="handleModify">Modify Val</button>
</div>
</template>
<script>
export default {
data() {
return {
message: 0,
};
},
components: {
Page,
},
methods: {
handleModify() {
for (let i = 0; i <= 100; i++) {
this.message = i;
}
},
}
};
</script>
message的值虽然改了100次,但是视图只更新了一次,用的最后一次的值100。底层原理就是Event Loop机制,同步代码先执行,然后才把异步任务放到调用栈里执行。源码里会同步通知更新,但执行实际地更新是异步的。就是说实际更新视图之前,值已经变成了100
core/observe/index.js
export function defineReactive (
obj: Object,
key: string,
val: any,
customSetter?: ?Function,
shallow?: boolean
) {
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
// 通知更新
dep.notify()
}
})
}
core/observe/dep.js
notify () {
// stabilize the subscriber list first
const subs = this.subs.slice()
if (process.env.NODE_ENV !== 'production' && !config.async) {
// subs aren't sorted in scheduler if not running async
// we need to sort them now to make sure they fire in correct
// order
subs.sort((a, b) => a.id - b.id)
}
// 遍历当前值相关的watcher对象,执行watcher的update()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
core/observe/watcher.js
update () {
/* istanbul ignore else */
if (this.lazy) {
this.dirty = true
} else if (this.sync) {
this.run()
} else {
// 执行这,把当前的watch传进去
queueWatcher(this)
}
}
core/observe/scheduler.js
function flushSchedulerQueue () {
currentFlushTimestamp = getNow()
flushing = true
let watcher, id
// 排序是为了确保组件从父级更新到子级。(因为父母总是在子对象之前创建)
queue.sort((a, b) => a.id - b.id)
// do not cache length because more watchers might be pushed
// as we run existing watchers
for (index = 0; index < queue.length; index++) {
watcher = queue[index]
if (watcher.before) {
watcher.before()
}
id = watcher.id
has[id] = null
// 去执行get->gettter即updateComponent
watcher.run()
// in dev build, check and stop circular updates.
if (process.env.NODE_ENV !== 'production' && has[id] != null) {
circular[id] = (circular[id] || 0) + 1
if (circular[id] > MAX_UPDATE_COUNT) {
warn(
'You may have an infinite update loop ' + (
watcher.user
? `in watcher with expression "${watcher.expression}"`
: `in a component render function.`
),
watcher.vm
)
break
}
}
}
// keep copies of post queues before resetting state
const activatedQueue = activatedChildren.slice()
const updatedQueue = queue.slice()
resetSchedulerState()
// call component updated and activated hooks
callActivatedHooks(activatedQueue)
callUpdatedHooks(updatedQueue)
// devtool hook
/* istanbul ignore if */
if (devtools && config.devtools) {
devtools.emit('flush')
}
}
export function queueWatcher (watcher: Watcher) {
const id = watcher.id
// 如果该watcher对象没之前有放入到队列过,放入队列
// 连续的修改值,会触发连续的dep.notify(), 那样就会连续的放入多个当前的watcher对象,
// 所以这里去个重
if (has[id] == null) {
// 下次带有这个id的wather对象再进来时,就不会放入到队列了
has[id] = true
if (!flushing) {
// 把wather放进队列
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 = true
if (process.env.NODE_ENV !== 'production' && !config.async) {
flushSchedulerQueue()
return
}
// 看这,执行nextTick
nextTick(flushSchedulerQueue)
}
}
}
flushSchedulerQueue函数的作用就是的把值相关的watcher对象的queue数组遍历,挨个执行一下wantcher.run()。进而执行到updateComponent 这个还不算完,flushSchedulerQueue并不会立即执行,看看 nextTick(flushSchedulerQueue)拿它干啥?
// flushCallbacks用来执行队列,执行这个方法的时候,那个修改的值早就是100了
function flushCallbacks () {
pending = false
const copies = callbacks.slice(0)
callbacks.length = 0
for (let i = 0; i < copies.length; i++) {
copies[i]()
}
}
// 为啥是异步,在这里
let timerFunc
if (typeof Promise !== 'undefined' && isNative(Promise)) {
const p = Promise.resolve()
timerFunc = () => {
p.then(flushCallbacks)
// In problematic UIWebViews, Promise.then doesn't completely break, but
// it can get stuck in a weird state where callbacks are pushed into the
// microtask queue but the queue isn't being flushed, until the browser
// needs to do some other work, e.g. handle a timer. Therefore we can
// "force" the microtask queue to be flushed by adding an empty timer.
if (isIOS) setTimeout(noop)
}
isUsingMicroTask = true
} else if (!isIE && typeof MutationObserver !== 'undefined' && (
isNative(MutationObserver) ||
// PhantomJS and iOS 7.x
MutationObserver.toString() === '[object MutationObserverConstructor]'
)) {
// Use MutationObserver where native Promise is not available,
// e.g. PhantomJS, iOS7, Android 4.4
// (#6466 MutationObserver is unreliable in IE11)
let counter = 1
const observer = new MutationObserver(flushCallbacks)
const textNode = document.createTextNode(String(counter))
observer.observe(textNode, {
characterData: true
})
timerFunc = () => {
counter = (counter + 1) % 2
textNode.data = String(counter)
}
isUsingMicroTask = true
} else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) {
// Fallback to setImmediate.
// Technically it leverages the (macro) task queue,
// but it is still a better choice than setTimeout.
timerFunc = () => {
setImmediate(flushCallbacks)
}
} else {
// Fallback to setTimeout.
timerFunc = () => {
setTimeout(flushCallbacks, 0)
}
}
// cb 就是flushSchedulerQueue
export function nextTick (cb?: Function, ctx?: Object) {
let _resolve
// 把又包了一层函数,把它push进callbacks队列
callbacks.push(() => {
if (cb) {
try {
// flushSchedulerQueue被调用
cb.call(ctx)
} catch (e) {
handleError(e, ctx, 'nextTick')
}
} else if (_resolve) {
_resolve(ctx)
}
})
if (!pending) {
pending = true
// 异步执行队列
timerFunc()
}
// $flow-disable-line
if (!cb && typeof Promise !== 'undefined') {
return new Promise(resolve => {
_resolve = resolve
})
}
}
原型上的$nextTick也是执行的这个nextTick(cb,ctx); core/instace/render.js
Vue.prototype.$nextTick = function (fn: Function) {
return nextTick(fn, this)
}
比如
this.message = 'abc'
this.$nextTick(function () {
do something...
})
this.$nextTick会把回调方法加在异步队列callbacks的最后,前面是更新视图的任务,所以这样就保证了this.$nextTick里的回调函数将在 DOM 更新完成后被调用