描述:html
在(一)中其實已經把Vue做爲MVVM的框架中數據流相關跑了一遍。這一章咱們先看mount這一步,這樣Vue大的主線就基本跑通了。而後咱們再去看compile,v-bind等功能性模塊的處理。
path: platforms\web\entry-runtime-with-compiler.js 這裏對本來的公用$mount方法進行了代理.實際的直接方法是core/instance/lifecycle.js中的mountComponent方法。 根據組件模板的不一樣形式這裏出現了兩個分支,一個核心: 分支: 一、組件參數中有render屬性:執行mount.call(this, el, hydrating) 二、組件參數中沒有render屬性:將template/el轉換爲render方法 核心:Vue.prototype._render公共方法
/* @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 }) //這裏代理了vue實例的$mount方法 const mount = Vue.prototype.$mount Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component { el = el && query(el) /* istanbul ignore if */ 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 // resolve template/el and convert to render function //解析template/el轉化爲render方法。這裏就是一個大的分支,咱們能夠將它稱爲render分支 if (!options.render) { //若是沒有傳入render方法,且template參數存在,那麼就開始解析模板,這就是compile的開始 let template = options.template 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) { template = getOuterHTML(el) } if (template) { /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.performance && mark) { mark('compile') } const { render, staticRenderFns } = compileToFunctions(template, { 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
//最多見 new Vue({ el: '#app', router, render: h => h(App), });
若是有render方法,那麼就會調用公共mount方法,而後判斷一下平臺後直接調用mountComponent方法vue
// public mount method //入口中被代理的公用方法就是它,path : platforms\web\runtime\index.js Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean ): Component { //由於是公用方法因此在這裏有從新判斷了一些el,其實若是有render屬性的話,這裏el就已是DOM對象了 el = el && inBrowser ? query(el) : undefined return mountComponent(this, el, hydrating) }
接下來就是mountComponent。這裏面有一個關鍵點 vm._watcher = new Watcher(vm, updateComponent, noop),這個其實就是上篇中說到的依賴收集的一個觸發點。你能夠想一想,組件在這個時候其實數據已經完成了響應式轉換,就坐等收集依賴了,也就是坐等被第一次使用訪問了。node
export function mountComponent ( vm: Component, el: ?Element, hydrating?: boolean ): Component { vm.$el = el //這個判斷其實只是在配置默認render方法createEmptyVNode 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 ) } } } //執行beforeMount回調函數 callHook(vm, 'beforeMount') //這個updateComponent方法很重要,其實能夠將它與Watcher中的參數expOrFn聯繫起來。他就是一個Watcher實例的值的獲取過程,訂閱者的一種真實身份。 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 = () => { //實際方法,被Watcher.getter方法的執行給調用回來了,在這裏先直接執行vm.render,這個就是compile的觸發點 vm._update(vm._render(), hydrating) } } //開始生產updateComponent這個動做的訂閱者了,生產過程當中調用Watcher.getter方法時又會回來執行這個updateComponent方法。看上面兩排 vm._watcher = new Watcher(vm, updateComponent, noop) 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 }
path : core\instance\render.js
Vue.prototype._render()這個方法的調用在整個源碼中就兩處,vm._render()和child._render()。
從中能夠理解到一個執行鏈條:web
$mount -> new Watcher -> watcher.getter -> updateComponent -> vm._update -> vm._render -> vm.createElement -> createComponent(若是存在子組件,調用createElement,若是沒有執行createElement) 在render的這一個層面上的出發點,都是來自於vm.$options.render函數,這也是爲何在Vue.prototype.$mount方法中會對vm.$options.render進行判斷處理從而分出有render函數和沒有render函數兩種不一樣的處理方式
看一下vm._render源碼:app
export function renderMixin (Vue: Class<Component>) { // install runtime convenience helpers installRenderHelpers(Vue.prototype) Vue.prototype.$nextTick = function (fn: Function) { return nextTick(fn, this) } Vue.prototype._render = function (): VNode { const vm: Component = this const { render, _parentVnode } = vm.$options //若是父組件尚未更新,那麼就先把子組件存在vm.$slots中 if (vm._isMounted) { // if the parent didn't update, the slot nodes will be the ones from // last render. They need to be cloned to ensure "freshness" for this render. for (const key in vm.$slots) { const slot = vm.$slots[key] if (slot._rendered) { vm.$slots[key] = cloneVNodes(slot, true /* deep */) } } } //做用域插槽 vm.$scopedSlots = (_parentVnode && _parentVnode.data.scopedSlots) || emptyObject // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode // render self let vnode try { //執行$options.render,若是沒傳的就是一個默認的VNode實例。最後都會去掉用createElement公用方法core\vdom\create-element.js。這個就是大工程了。 vnode = render.call(vm._renderProxy, vm.$createElement) } catch (e) { handleError(e, vm, `render`) // return error render result, // or previous vnode to prevent render error causing blank component /* istanbul ignore else */ if (process.env.NODE_ENV !== 'production') { if (vm.$options.renderError) { try { vnode = vm.$options.renderError.call(vm._renderProxy, vm.$createElement, e) } catch (e) { handleError(e, vm, `renderError`) vnode = vm._vnode } } else { vnode = vm._vnode } } else { vnode = vm._vnode } } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if (process.env.NODE_ENV !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ) } vnode = createEmptyVNode() } // set parent vnode.parent = _parentVnode return vnode } }
三、_createElement, createComponent框架
path : core\vdom\create-element.js _createElement(context, tag, data, children, normalizationType)
export function _createElement ( context: Component, tag?: string | Class<Component> | Function | Object, data?: VNodeData, children?: any, normalizationType?: number ): VNode { //可使用 if (isDef(data) && isDef((data: any).__ob__)) { process.env.NODE_ENV !== 'production' && warn( `Avoid using observed data object as vnode data: ${JSON.stringify(data)}\n` + 'Always create fresh vnode data objects in each render!', context ) return createEmptyVNode() } // object syntax in v-bind if (isDef(data) && isDef(data.is)) { tag = data.is } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // warn against non-primitive key if (process.env.NODE_ENV !== 'production' && isDef(data) && isDef(data.key) && !isPrimitive(data.key) ) { warn( 'Avoid using non-primitive value as key, ' + 'use string/number value instead.', context ) } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function' ) { data = data || {} data.scopedSlots = { default: children[0] } children.length = 0 } 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 (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 (isDef(vnode)) { if (ns) applyNS(vnode, ns) return vnode } else { return createEmptyVNode() } }
path : core\vdom\create-component.js createComponent (Ctor, data, context, children, tag) Ctor : 組件Module信息,最後與會被處理成vm實例對象 data : 組件數據 context : 當前Vue組件 children : 自組件 tag :組件名
const hooksToMerge = Object.keys(componentVNodeHooks) export function createComponent ( Ctor: Class<Component> | Function | Object | void, data: ?VNodeData, context: Component, children: ?Array<VNode>, tag?: string ): VNode | void { //Ctor不能爲undefined || null if (isUndef(Ctor)) { return } // const baseCtor = context.$options._base // plain options object: turn it into a constructor // 若是Ctor爲對象,合併到vm數據,構建Ctor if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor) } // if at this stage it's not a constructor or an async component factory, // reject. if (typeof Ctor !== 'function') { if (process.env.NODE_ENV !== 'production') { warn(`Invalid Component definition: ${String(Ctor)}`, context) } return } // 異步組件 let asyncFactory if (isUndef(Ctor.cid)) { asyncFactory = Ctor Ctor = resolveAsyncComponent(asyncFactory, baseCtor, context) if (Ctor === undefined) { // return a placeholder node for async component, which is rendered // as a comment node but preserves all the raw information for the node. // the information will be used for async server-rendering and hydration. return createAsyncPlaceholder( asyncFactory, data, context, children, tag ) } } data = data || {} // resolve constructor options in case global mixins are applied after // component constructor creation //解析組件實例的options resolveConstructorOptions(Ctor) // transform component v-model data into props & events if (isDef(data.model)) { transformModel(Ctor.options, data) } // extract props const propsData = extractPropsFromVNodeData(data, Ctor, tag) // functional component if (isTrue(Ctor.options.functional)) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners const listeners = data.on // replace with listeners with .native modifier // so it gets processed during parent component patch. data.on = data.nativeOn if (isTrue(Ctor.options.abstract)) { // abstract components do not keep anything // other than props & listeners & slot // work around flow const slot = data.slot data = {} if (slot) { data.slot = slot } } // merge component management hooks onto the placeholder node // 合併鉤子函數 init 、 destroy 、 insert 、prepatch mergeHooks(data) // return a placeholder vnode // 最終目的生成一個vnode,而後就是一路的return出去 const name = Ctor.options.name || tag const vnode = new VNode( `vue-component-${Ctor.cid}${name ? `-${name}` : ''}`, data, undefined, undefined, undefined, context, { Ctor, propsData, listeners, tag, children }, asyncFactory ) return vnode }
過程線條:dom
$mount -> new Watcher -> watcher.getter -> updateComponent -> vm._update -> vm._render -> vm.createElement -> createComponent(若是存在子組件,調用createElement,若是沒有執行createElement)
上面這個線條中其實都圍繞着vm.$options進行render組件。如今大部分項目都是使用的.vue組件進行開發,因此使得對組件的配置對象不太敏感。
由於將.vue的內容轉化爲Vue組件配置模式的過程都被vue-loader處理(咱們在require組件時處理的),其中就包括將template轉換爲render函數的關鍵。咱們也能夠定義一個配置型的組件,而後觸發Vue$3.prototype.$mount中的mark('compile')進行處理。可是我以爲意義不是太大。
過程,這也是致使咱們在源碼運行中老是看見在有無render函數分支,的時候老是能看見render函數,而後就進入對組件 vm._update(vm._render(), hydrating)。
咱們先記住這條主線,下一章咱們進入到vue-loader中去看看異步