开始
这篇就讲最后的部分,挂载el元素
vm.$mount(vm.$options.el);
复制代码
首先,在箭头处定义了一个mount方法,挂在原型上
缓存的 mount的函数如下Vue.prototype.$mount = function (
el,
hydrating
) {
//获得dom元素
el = el && inBrowser ? query(el) : undefined;
return mountComponent(this, el, hydrating)
};
复制代码
再看看挂载函数mountComponent
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
//没有写render函数的话,需要template或者el
if (!vm.$options.render) {
//创建一个空的vnode
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
//没写render但用了template
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') || vm.$options.el || el) {
warn(
// runtime-only 这个版本的vue,不会编译template到render函数里面,要不就预编译,要不装
// 包含编译的版本 runtime-compiler
'You are using the runtime-only build of Vue where the template ' +
'compiler is not available. Either pre-compile the templates into ' +
'render functions, or use the compiler-included build.',
vm
)
} else {
//没有template和render
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
//调用一个beforeMount的钩子 ,先不讲
callHook(vm, 'beforeMount')
let updateComponent
/* istanbul ignore if */
//make就是一些性能的埋点
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
updateComponent = () => {
const name = vm._name
const id = vm._uid
const startTag = `vue-perf-start:${id}`
const endTag = `vue-perf-end:${id}`
mark(startTag)
const vnode = vm._render()
mark(endTag)
measure(`vue ${name} render`, startTag, endTag)
mark(startTag)
vm._update(vnode, hydrating)
mark(endTag)
measure(`vue ${name} patch`, startTag, endTag)
}
} else {
//更新组件的 ,执行看下面的new Watcher,
updateComponent = () => {
//这个会调用,通过new Watcher 会调用 ,触发一次渲染
vm._update(vm._render(), hydrating)
}
}
// we set this to vm._watcher inside the watcher's constructor
// since the watcher's initial patch may call $forceUpdate (e.g. inside child
// component's mounted hook), which relies on vm._watcher being already defined
//看observer目录上的watcher.js
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// manually mounted instance, call mounted on self
// mounted is called for render-created child components in its inserted hook
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
复制代码
上面的挂载函数主要是
- 判断了下是否有render,el,template(运行时版本没有template编译器,不能写template标签,用render代替)
- 调用了一个钩子,
- 调用_render函数
总结
挂载的过程就是先获得el的dom元素,执行挂载的mountComponent方法,我这里写了render的函数,所以直接执行callHook(vm, 'beforeMount'),接着是 updateComponent 的调用,(通过new Watcher实例化的时候调用的,具体调用过程不讲先,只需要知道会触发updateComponent 的调用),updateComponent 会干什么事呢? 下节讲 see u