vue 掛載到dom 元素后發生了什么
前一篇文章分析了new vue() 初始化時所執行的操作,主要包括調用vue._init 執行一系列的初始化,包括生命周期,事件系統,beforeCreate和Created hook,在在這里發生,重點分析了 initState,即對我們常用到的data props computed 等等進行的初始化,最后,執行$mount 對dom進行了掛載,本篇文章將對掛載后所發生的事情進行進一步闡述,
Vue.prototype.$mount = function ( el?: string | Element, hydrating?: boolean): Component { el = el && inBrowser ? query(el) : undefined return mountComponent(this, el, hydrating)}mount 的代碼很簡單,直接執行了moutComponent方法,
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') 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._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 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}moutComponent 這里判斷了render函數,正常開發過程中,對于dom的寫法有很多種,可以直接寫templete,也可以寫render函數,也可以直接把dom寫在掛載元素里面,但是在編譯階段(通常是通過webpack執行的),統統會把這些寫法都編譯成render函數,所以,最后執行的都是render函數,判斷完render可以看到,beforeMount hook在這里執行,最后執行了new Watcher() 我們進入new Watcher
新聞熱點
疑難解答
圖片精選