1.初始化操作
看一下源码的初始化方法:
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
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)
}
initMixin(Vue) //实现_init方法
stateMixin(Vue) //状态相关的api
eventsMixin(Vue) //事件相关api
lifecycleMixin(Vue) //生命周期相关api
renderMixin(Vue) //渲染api
export default Vue
执行new Vue的时候就是执行this._init()这个方法:
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// 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 {
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)
initRender(vm)
callHook(vm, 'beforeCreate')
initInjections(vm) // resolve injections before data/props
initState(vm)
initProvide(vm) // resolve provide after data/props
callHook(vm, '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)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
}
这个方法首先整合options选项,然后进行一系列的初始化操作,包括初始化事件、生命周期 props、 methods、 data、 computed 与 watch。最后判断是否有el进行挂载。
2.挂载mount
挂载主要分为两步,render和update。
render
如果没有render,而是template模板的话,需要通过compile模块将其转化为render函数。通过render渲染成VNode。
createElement方法,这里不做展开
update
updata()方法将虚拟dom转换成真实dom显示在页面上。这个过程会先执行patch方法对新旧虚拟dom进行差异对比,这个也就是vue中的diff算法。
打开vdom/patch.js,具体不展开