1.分析入口:
Vue本身是一个构造函数,函数内首先执行的是对options内容的初始化处理。与此同时函数外面执行混入的初始化操作。
function Vue(options) {
if (__DEV__ && !(this instanceof Vue)) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
//@ts-expect-error Vue has function type
initMixin(Vue)
//@ts-expect-error Vue has function type
stateMixin(Vue)
//@ts-expect-error Vue has function type
eventsMixin(Vue)
//@ts-expect-error Vue has function type
lifecycleMixin(Vue)
//@ts-expect-error Vue has function type
renderMixin(Vue)
_init方法是绑定在Vue的原型对象上的
export function initMixin(Vue: typeof Component) {
Vue.prototype._init = function (options?: Record<string, any>) {
const vm: Component = this
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (__DEV__ && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to mark this as a Vue instance without having to do instanceof
// check
vm._isVue = true
// avoid instances from being observed
vm.__v_skip = true
// effect scope
vm._scope = new EffectScope(true /* detached */)
vm._scope._vm = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options as any)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor as any),
options || {},
vm
)
}
/* istanbul ignore else */
if (__DEV__) {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm
initLifecycle(vm)
initEvents(vm)
initRender(vm)
callHook(vm, 'beforeCreate', undefined, false /* setContext */)
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created')
/* istanbul ignore if */
if (__DEV__ && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`vue ${vm._name} init`, startTag, endTag)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
}
2.dep与watcher之间的联系请看下图:
3.这里涉及的知识点:
- Object.defineProperty进行数据的拦截处理
- 观察订阅者模式:
// 观察订阅者模式实例:
class Dep {
target = null
constructor () {
this.subs = []
}
depend (target) {
if (target && !this.subs.includes(target)) {
this.subs.push(target)
}
}
notify () {
this.subs.forEach(v => {
v()
})
}
}
let data = {
a: 0,
b: 1,
total: 0
};
Object.keys(data).forEach(key=> {
let temp = data[key]
const dep = new Dep()
Object.defineProperty(data, key,{
get() {
if (Dep.target) {
dep.depend(Dep.target)
}
return temp
},
set(val) {
if (temp!=val) {
temp = val
dep.notify()
}
}
})
})
function watcher (fn) {
Dep.target = fn
Dep.target()
Dep.target = null
}
watcher(()=>{
data.total = data.a + data.b
})
参考自:
https://cn.vuejs.org/v2/guide/reactivity.html
vue源码的github地址:https://github.com/vuejs/vue