接上一章vue2 源码解析(一)入口文件
流程图
代码分析
1. 片段一
文件:vue\src\platforms\web\entry-runtime-with-compiler.js
源码:
/* @flow */
import config from 'core/config'
import { warn, cached } from 'core/util/index'
import { mark, measure } from 'core/util/perf'
import Vue from './runtime/index'
import { query } from './util/index'
import { compileToFunctions } from './compiler/index'
import { shouldDecodeNewlines, shouldDecodeNewlinesForHref } from './util/compat'
const idToTemplate = cached(id => {
const el = query(id)
return el && el.innerHTML
})
// 扩展$mount方法(这个扩展主要是是获取render或者el、template转换为render)
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,// 字符串或dom元素
hydrating?: boolean
): Component {
// 获取指定el元素
el = el && query(el)
/* istanbul ignore if */
// el不能为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,所以优先级最高
// resolve template/el and convert to render function
if (!options.render) {
let template = options.template
// 在判断是否添加了template,如果没有则使用el
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && !template) {
warn(
`Template element not found or is empty: ${options.template}`,
this
)
}
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
if (process.env.NODE_ENV !== 'production') {
warn('invalid template option:' + template, this)
}
return this
}
} else if (el) {
// 没有render、template的话使用el选项。
template = getOuterHTML(el);//还是要转化为template
}
if (template) {
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
mark('compile')
}
// 将template编译为render(最主要的:compileToFunctions核心函数)
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
/* istanbul ignore if */
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)
}
/**
* Get outerHTML of elements, taking care
* of SVG elements in IE as well.
*/
function getOuterHTML (el: Element): string {
if (el.outerHTML) {
return el.outerHTML
} else {
const container = document.createElement('div')
container.appendChild(el.cloneNode(true))
return container.innerHTML
}
}
Vue.compile = compileToFunctions
export default Vue
思路:
主要是扩展$mount方法。
- 获取el元素。判断不能为html或者body
- 编译。判断是否配置了render,如果没有,再判断是否配置了template,最后判断el。由上可知优先级:render > template > el。如果是template或者el的配置,都会通过compileToFunctions这个函数编译为render。render效率最高。
-
调用$mount方法
2. 片段二
文件:vue\src\platforms\web\runtime\index.js。进入$mount方法文件
源码:
// install platform patch function
/*
设置patch函数
1. 初始化 虚拟dom(vdom)转真实dom
2. update diff 更新操作
*/
Vue.prototype.__patch__ = inBrowser ? patch : noop
// public mount method
/*
设置$mount函数
*/
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
思路:
- 执行mountComponent。其中$mount 可以传入el挂载元素字符串,或者直接dom对象
3. 片段三
文件:vue\src\core\instance\lifecycle.js。进入mountComponent方法文件
源码:
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
vm.$el = el
if (!vm.$options.render) {
vm.$options.render = createEmptyVNode
if (process.env.NODE_ENV !== 'production') {
/* istanbul ignore if */
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
)
}
}
}
callHook(vm, 'beforeMount');// 生命周期钩子
// 定义updateComponent方法,在watch回调时调用
let updateComponent
/* istanbul ignore if */
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._render() 生成虚拟dom
// vm._update() 虚拟dom渲染为真实dom
vm._update(vm._render(), hydrating)
}
}
/*
Watcher 会在回调函数中调用updateComponent,生成虚拟dom,然后渲染成真实dom
Watcher 在这里起到两个作用,一个是初始化的时候会执行回调函数,另一个是当 vm 实例中的监测的数据发生变化的时候执行回调函数
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
*/
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate');// 生命周期钩子
}
}
}, true /* isRenderWatcher */)
hydrating = false
/*
vm.$vnode==null 时,表示当前为根 Vue 的实例
manually mounted instance, call mounted on self
mounted is called for render-created child components in its inserted hook
*/
if (vm.$vnode == null) {
// 实例已经挂载,执行mounted生命周期钩子
vm._isMounted = true
callHook(vm, 'mounted');// 生命周期钩子
}
return vm
}
思路:
- 执行生命周期钩子:beforeMount
-
定义updateComponent方法,用于将虚拟dom渲染为真实dom
-
实例化new Watcher。用于初始化的时候执行回调函数updateComponent,还有就是监测的数据发生变化执行回调,实现渲染真实dom
-
判断是否Vue跟的实例,如果是执行生命周期钩子:mounted
-
最后返回整个实例,结束
文件地址:github