上一篇:Vue2.x 源码 - 初始化:stateMixin(Vue)、eventsMixin(Vue)、lifecycleMixin(Vue)、renderMixin(Vue)
Vue 中是通过 $mount 实例方法来挂载 vm 的;然而这个方法在很多个文件里都有定义:src/platform/web/entry-runtime-with-compiler.js 、src/platform/web/runtime/index.js 、 src/platform/weex/runtime/index.js 。$mount方法的实现和平台、构建方式有关;这里我们主要看一下 web 文件夹下的两种实现。
1、带 compiler 版本的 $mount
在 src/platform/web/entry-runtime-with-compiler.js 文件中
//缓存原型上的 $mount 方法
const mount = Vue.prototype.$mount
//重新定义 $mount 方法
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
//选择器没有则创建一个 div,有则返回
el = el && query(el)
// 不可把 Vue 挂载到 html body 上
if (el === document.body || el === document.documentElement) {
process.env.NODE_ENV !== 'production' && warn(
`Do not mount Vue to <html> or <body> - mount to normal elements instead.`
)
return this
}
//获取参数
const options = this.$options
//没有 render , 解析模板/el并转换为渲染函数
if (!options.render) {
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
//获取 template 选择器的 innerHtml
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
//如果元素节点则直接返回 innerHtml
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
//获取元素的outerHTML,同时处理IE中的SVG元素
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
//日志 开始编译
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
//编译生成render
const { render, staticRenderFns } = compileToFunctions(template, {
outputSourceRange: process.env.NODE_ENV !== 'production',
shouldDecodeNewlines,
shouldDecodeNewlinesForHref,
delimiters: options.delimiters,
comments: options.comments
}, this)
options.render = render
options.staticRenderFns = staticRenderFns
//日志 编译结束
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile end')
measure(`vue ${this._name} compile`, 'compile', 'compile end')
}
}
}
//调⽤原先原型上的 $mount ⽅法挂载
return mount.call(this, el, hydrating)
}
首先缓存原型上的 $mount 方法,然后重新定义该方法;首先,对 el 做了限制,Vue 不能挂载在 html 、body 根节点上;如果 options 里面没有定义 render 方法,则把 el 或者 template 字符串转换成 render 方法,template 是 字符串或者是元素节点则返回 innerHtml,el 获取 outerHtml ;也就是说 Vue 所有组件的渲染都需要转成 render 方法;然后会调用 compileToFunctions 方法来实现编译;然后调用原型上原先的 $mount 方法挂载。
compileToFunctions 方法是把模板 template 编译生成 render 和 staticRenderFns;编译参考:(Vue2.x 源码 - 编译过程(compile))。
这里有个原先原型的 $mount 方法,其实就是在 src/platform/web/runtime/index.js 文件里定义的,下面我们来看看:
2、不带 compiler 的 $mount
在 src/platform/web/runtime/index.js 文件中;
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean //服务端渲染相关参数
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
$mount ⽅法实际上会去调⽤ mountComponent ⽅法,这个⽅法定义在 src/core/instance/lifecycle.js ⽂件中:
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
//render未定义
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
//您正在使用Vue的仅运行时构建,其中模板编译器不可用。要么将模板预编译成呈现函数,要么使用编译器包含的构建。
if (process.env.NODE_ENV !== 'production') {
if ((vm.$options.template && vm.$options.template.charAt(0) !== '#') ||
vm.$options.el || el) {
warn(
'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 {
//挂载组件失败:模板或呈现函数未定义
warn(
'Failed to mount component: template or render function not defined.',
vm
)
}
}
}
//beforeMount生命周期钩子
callHook(vm, 'beforeMount')
let updateComponent
//性能调试,常规操作是走的 else
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 {
updateComponent = () => {
vm._update(vm._render(), hydrating)
}
}
// 实例化一个 watcher,调用updateComponent,然后调用_update更新DOM
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
hydrating = false
// 为根节点时,表明实例已经挂载,调用 mounted生命周期钩子
if (vm.$vnode == null) {
vm._isMounted = true
callHook(vm, 'mounted')
}
return vm
}
mountComponent核⼼就是先调⽤ vm._render ⽅法先⽣成虚拟 Node(参考:Vue2.x 源码 - render 函数生成 VNode),再 实例化⼀个渲染 Watcher ,在它的回调函数中会调⽤ updateComponent ⽅法,最终调⽤ vm._update 更新 DOM。