我们在上一篇了解了发布-订阅模式的实现,这一篇总结下Vue是怎么利用发布-订阅模式来实现双向数据绑定的。
1. Vue 构造函数的实现
首先我们使用vue构造函数去实例化了一个vue
实例。传入了props
, data
, watch
, methods
等属性。在实例化的过程中,Vue
提供的构造函数就使用我们传入的options
去完成数据的依赖管理,初始化的过程只有一次,但是数据的依赖管理的次数不止一次。
Vue
的构造函数的实现:(src/core/instance/index.js)
// vue的构造函数实现
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
//开始初始化
this._init(options)
}
// 对Vue进行mixin,即在其原型上添加方法
// Vue.prototype.* = function(){}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
当我们调用new Vue的时候,事实上就调用的Vue原型上的_init方法。
export function initMixin (Vue: Class<Component>) {
//initMixin 在vue原型上增加 _init 方法,新建一个vue实例并传入options参数
Vue.prototype._init = function (options?: Object) {
const vm: Component = this // 新的Vue实例
// a uid
vm._uid = uid++
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to avoid this being observed
vm._isVue = 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)
} else {
//将传入的options选项挂载到vm.$options属性上
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// expose real self
vm._self = vm // 自身的实例
// 接下来所有的操作都是在这个实例上添加方法
initLifecycle(vm)// 初始化生命周期
initEvents(vm)// 初始化事件 vm.events 主要提供vm实例上的$on/emit/off等方法
initRender(vm)// 初始化渲染函数,在vm上绑定$createElement方法
callHook(vm, 'beforeCreate')// 调用beforeCreate钩子函数并且触发beforeCreate钩子事件
initInjections(vm) // resolve injections before data/props
initState(vm) // Observe 添加对data的监听, 将data转化为getters/setters
initProvide(vm) // resolve provide after data/props
callHook(vm, 'created') // created钩子函数的执行
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`vue ${vm._name} init`, startTag, endTag)
}
// vm挂载根元素
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
}
其中对data添加监听, 将data转化为getters/setters是在 initState(vm) 中完成的。(src/core/instance/state.js)
// 初始化props、methods、data、computed与watch
export function initState (vm: Component) {
vm._watchers = [] // 首先在vm上初始化一个_watchers数组,缓存这个vm上的所有watcher
const opts = vm.$options // 获取options,包括在new Vue传入的,同时还包括了Vue所继承的options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {// 该组件没有data的时候绑定一个空对象
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
我们以对props属性为例,看下Vue怎么进行依赖收集。
function initProps (vm: Component, propsOptions: Object) {
const propsData = vm.$options.propsData || {}
const props = vm._props = {}
// cache prop keys so that future props updates can iterate using Array
// i