new Vue() 做了什么漫萄?
src\core\instance\index.js
...
function Vue (options) {
...
this._init(options)
}
...
export default Vue
簡單明了:執(zhí)行了this._init(options)
操作
那 _init
函數(shù)又做了啥卷员??
src\core\instance\init.js
Vue.prototype._init = function (options?: Object) {
...
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')
...
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
}
顯然腾务,做了這三件事:
- 執(zhí)行了一堆初始化操作
initLifecycle毕骡、initEvents、initRender窑睁、initInjections挺峡、initState、initProvide
- 調(diào)用了倆生命周期鉤子
- 執(zhí)行
vm.$mount(vm.$options.el)
這里担钮,我們看主流程 $mount
操作橱赠,$mount
基于不同的平臺(tái)(web/weex)和構(gòu)建方式有不同的實(shí)現(xiàn),主要看 web 端編譯版本實(shí)現(xiàn)
src\platforms\web\entry-runtime-with-compiler.js
// 緩存原型上定義的 $mount 函數(shù)
const mount = Vue.prototype.$mount
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && query(el)
const options = this.$options
// resolve template/el and convert to render function
if (!options.render) {
// 申明并處理 template
let template = options.template
if (template) {
if (typeof template === 'string') {
if (template.charAt(0) === '#') {
template = idToTemplate(template)
}
} else if (template.nodeType) {
template = template.innerHTML
} else {
return this
}
} else if (el) {
template = getOuterHTML(el)
}
if (template) {
// 關(guān)鍵操作:利用 compileToFunctions 編譯生成 render 函數(shù)
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
}
}
// 利用原型上定義的 $mount 函數(shù)實(shí)現(xiàn)掛載
return mount.call(this, el, hydrating)
}
src\platforms\web\runtime\index.js
// public mount method
Vue.prototype.$mount = function (
el?: string | Element,
hydrating?: boolean
): Component {
el = el && inBrowser ? query(el) : undefined
return mountComponent(this, el, hydrating)
}
src\core\instance\lifecycle.js
export function mountComponent (
vm: Component,
el: ?Element,
hydrating?: boolean
): Component {
...
// 調(diào)用 beforeMount 鉤子
callHook(vm, 'beforeMount')
// 申明并賦值 updateComponent 函數(shù)
let updateComponent
updateComponent = () => {
...
const vnode = vm._render() // 調(diào)用 _render() 生成 vnode
vm._update(vnode, hydrating) // 調(diào)用 _update() 更新 DOM
...
}
// 初始化一個(gè) render watcher
new Watcher(vm, updateComponent, noop, {
before () {
if (vm._isMounted && !vm._isDestroyed) {
callHook(vm, 'beforeUpdate')
}
}
}, true /* isRenderWatcher */)
...
// 調(diào)用 mounted 鉤子
callHook(vm, 'mounted')
return vm
}
$mount 的核心即 mountComponent
函數(shù)箫津,該函數(shù)做了以下幾件事:
- 調(diào)用了
beforeMount狭姨、mounted
鉤子 - 申明并賦值
updateComponent
函數(shù) - 初始化了一個(gè) render watcher ,傳入
updateComponent
作為 update 執(zhí)行函數(shù)
src\core\observer\watcher.js
export default class Watcher {
...
constructor (
vm: Component,
expOrFn: string | Function,
cb: Function,
options?: ?Object,
isRenderWatcher?: boolean
) {
...
// parse expression for getter
if (typeof expOrFn === 'function') {
this.getter = expOrFn
}
this.value = this.lazy
? undefined
: this.get()
}
/**
* Evaluate the getter, and re-collect dependencies.
*/
get () {
...
value = this.getter.call(vm, vm)
...
}
}
在 watcher 初始化的過程中苏遥,會(huì)直接調(diào)用一次 updateComponent
函數(shù)
那么繼續(xù)回到 updateComponent
中來
const vnode = vm._render()
vm._update(vnode, hydrating)
updateComponent 做了兩件事:
- 調(diào)用
vm._render()
生成 vnode - 調(diào)用
vm._update()
更新 DOM
下面來看一下這倆函數(shù)的具體實(shí)現(xiàn)
src\core\instance\render.js
export function initRender (vm: Component) {
...
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
...
}
Vue.prototype._render = function (): VNode {
const vm: Component = this
const { render, _parentVnode } = vm.$options
let vnode
...
vnode = render.call(vm._renderProxy, vm.$createElement)
...
// set parent
vnode.parent = _parentVnode
return vnode
}
可以看出饼拍,_render
函數(shù)主要就是調(diào)用前面 $mount
中編譯好的 render 函數(shù),傳入?yún)?shù)vm.$createElement
田炭,返回一個(gè)虛擬DOM vnode师抄,而 $createElement
是在initRender
時(shí)定義好的一個(gè)函數(shù)(a, b, c, d) => createElement(vm, a, b, c, d, true)
src\core\vdom\create-element.js
export function createElement (
context: Component,
tag: any,
data: any,
children: any,
normalizationType: any,
alwaysNormalize: boolean
): VNode | Array<VNode> {
...
return _createElement(context, tag, data, children, normalizationType)
}
export function _createElement (
context: Component,
tag?: string | Class<Component> | Function | Object,
data?: VNodeData,
children?: any,
normalizationType?: number
): VNode | Array<VNode> {
// 將當(dāng)前實(shí)例的子節(jié)點(diǎn)數(shù)組處理成 vnode 數(shù)組
if (normalizationType === ALWAYS_NORMALIZE) {
children = normalizeChildren(children)
} else if (normalizationType === SIMPLE_NORMALIZE) {
children = simpleNormalizeChildren(children)
}
let vnode, ns
if (typeof tag === 'string') {
let Ctor
ns = (context.$vnode && context.$vnode.ns) || config.getTagNamespace(tag)
if (config.isReservedTag(tag)) {
// platform built-in elements
vnode = new VNode(
config.parsePlatformTagName(tag), data, children,
undefined, undefined, context
)
} else if ((!data || !data.pre) && isDef(Ctor = resolveAsset(context.$options, 'components', tag))) {
// component
vnode = createComponent(Ctor, data, context, children, tag)
} else {
// unknown or unlisted namespaced elements
// check at runtime because it may get assigned a namespace when its
// parent normalizes children
vnode = new VNode(
tag, data, children,
undefined, undefined, context
)
}
} else {
// direct component options / constructor
vnode = createComponent(tag, data, context, children)
}
if (Array.isArray(vnode)) {
return vnode
} else if (isDef(vnode)) {
...
return vnode
} else {
return createEmptyVNode()
}
}
總而言之,vm.$createElement
就是執(zhí)行_createElement
函數(shù)返回了一個(gè) vnode教硫,且父 vnode 的 children 也是 vnode 數(shù)組叨吮,形成了對應(yīng)描述 DOM tree 的 vnode tree
src\core\instance\lifecycle.js
Vue.prototype._update = function (vnode: VNode, hydrating?: boolean) {
...
if (!prevVnode) {
// initial render 初始化渲染調(diào)用
vm.$el = vm.__patch__(vm.$el, vnode, hydrating, false /* removeOnly */)
} else {
// updates update渲染調(diào)用
vm.$el = vm.__patch__(prevVnode, vnode)
}
...
}
vm._update()
中的操作就很少了,根據(jù)是初始化還是 update 場景傳入不同的參數(shù)去調(diào)用vm.__patch__
src\platforms\web\runtime\index.js
import { patch } from './patch'
// install platform patch function
Vue.prototype.__patch__ = inBrowser ? patch : noop
src\platforms\web\runtime\patch.js
import { createPatchFunction } from 'core/vdom/patch'
export const patch: Function = createPatchFunction({ nodeOps, modules })
src\core\vdom\patch.js
export function createPatchFunction (backend) {
...
return function patch (oldVnode, vnode, hydrating, removeOnly) {
...
invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch)
return vnode.elm
}
}
createPatchFunction 函數(shù)返回了一個(gè) patch 函數(shù)瞬矩,在 patch 中調(diào)用 nodeOps 中定義的方法操作元素的 create茶鉴、insert 和 remove,實(shí)現(xiàn) vnode 到 real DOM 的轉(zhuǎn)化
src\platforms\web\runtime\node-ops.js
總結(jié)
一張圖