关于Vue计算属性的原理我们在另一篇文章中已经进行了解析,想了解的可以点击这里。下面我们从源码角度来分析Vue watch的原理。
watch
watch属性是在initState阶段初始化的,我们直接看源码:
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
......
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
initWatch
function initWatch (vm: Component, watch: Object) {
for (const key in watch) {
const handler = watch[key]
if (Array.isArray(handler)) {
for (let i = 0; i < handler.length; i++) {
createWatcher(vm, key, handler[i])
}
} else {
createWatcher(vm, key, handler)
}
}
}
不论watch定义的是对象还是数组,都需要执行createWatcher:
function createWatcher (
vm: Component,
expOrFn: string | Function,
handler: any,
options?: Object
) {
if (isPlainObject(handler)) {
options = handler
handler = handler.handler
}
if (typeof handler === 'string') {
handler = vm[handler]
}
return vm.$watch(expOrFn, handler, options)
}
$watch : $watch可以全局调用,这里分析组件内定义的场景
Vue.prototype.$watch = function (
expOrFn: string | Function,
cb: any,
options?: Object
): Function {
const vm: Component = this
if (isPlainObject(cb)) {
return createWatcher(vm, expOrFn, cb, options)
}
options = options || {}
options.user = true
const watcher = new Watcher(vm, expOrFn, cb, options)
if (options.immediate) {
cb.call(vm, watcher.value)
}
return function unwatchFn () {
watcher.teardown()
}
}
user Watcher
下面我们看下实例化user Watcher:
export default class Watcher {
......
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
this.vm = vm
......
vm._watchers.push(this)
if (options) {
this.deep = !!options.deep
this.user = !!options.user
......
this.sync = !!options.sync
......
}
......
this.cb = cb
this.id = ++uid
this.active = true
...
this.deps = []
this.newDeps = []
this.depIds = new Set()
this.newDepIds = new Set()
this.expression = process.env.NODE_ENV !== 'production'
? expOrFn.toString()
: ''
if (typeof expOrFn === 'function') {
this.getter = expOrFn
} else {
this.getter = parsePath(expOrFn)
if (!this.getter) {
this.getter = function () {}
process.env.NODE_ENV !== 'production' && warn(
`Failed watching path: "${expOrFn}" ` +
'Watcher only accepts simple dot-delimited paths. ' +
'For full control, use a function instead.',
vm
)
}
}
this.value = this.get()
}
}
parsePath 的作用
parsePath是解析对象路径,watch的key支持’xx.xx.xx’的格式:
const bailRE = /[^\w.$]/
export function parsePath (path: string): any {
if (bailRE.test(path)) {
return
}
const segments = path.split('.')
return function (obj) {
for (let i = 0; i < segments.length; i++) {
if (!obj) return
obj = obj[segments[i]]
}
return obj
}
}
执行this.get():
get () {
pushTarget(this)
let value
const vm = this.vm
try {
value = this.getter.call(vm, vm)
} catch (e) {
if (this.user) {
handleError(e, vm, `getter for watcher "${this.expression}"`)
} else {
throw e
}
} finally {
if (this.deep) {
traverse(value)
}
popTarget()
this.cleanupDeps()
}
return value
}
deep 的原理
const seenObjects = new Set()
export function traverse (val: any) {
_traverse(val, seenObjects)
seenObjects.clear()
}
function _traverse (val: any, seen: SimpleSet) {
let i, keys
const isA = Array.isArray(val)
if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) {
return
}
if (val.__ob__) {
const depId = val.__ob__.dep.id
if (seen.has(depId)) {
return
}
seen.add(depId)
}
if (isA) {
i = val.length
while (i--) _traverse(val[i], seen)
} else {
keys = Object.keys(val)
i = keys.length
while (i--) _traverse(val[keys[i]], seen)
}
}
set是字典结构,可以理解为不含重复值的数组结构。traverse这个函数的作用,就是深度遍历这个对象,访问到对象上的所有值,访问到值的过程中,会触发值的getter函数,以收集这个user Watcher订阅者。这样,当深层次对象变化的时候,就会通知这个user Watcher做更新。
sync 的原理
当我们改变页面依赖的响应式数据的时候,页面的render Watcher会更新,其实这是个异步的过程,不了解的可以点击这里,参考这篇文章。
当依赖发生变化,通知watcher更新的时候,会执行Watcher的update:
update () {
if (this.computed) {
......
} else if (this.sync) {
this.run()
} else {
queueWatcher(this)
}
}
可以看到,当我们定义了sync属性,user watcher就可以直接同步更新,不需要进入nextTick。
总结
- watch中的属性可以以数组的形式,定义多个handler函数;
- user Watcher会在实例化Watcher求值的时候,访问属性值,以收集user Watcher作为订阅者;
- 定义了deep,会在实例化Watcher求值的时候,递归访问对象的所有深层属性值,以收集user Watcher作为订阅者;
- 定义了sync,在属性值变化触发user Watcher更新的时候,直接同步执行定义handler函数,不会放入nextTick中去执行;
- 定义了immediate,实例化Watcher之后,会立即触发定义的handler函数;
|