前言
本文是系列開篇,系列的主旨在于分享自己在閱讀vue源碼時(shí)的收獲和體會(huì)竹海,一方面是讓自己有個(gè)總結(jié)晰骑,另一方面幫助想要理解vue源碼的同學(xué)有個(gè)可以參考的東西权埠。
寫文章的時(shí)候vue版本為2.4.2
開篇
我們來看一下官網(wǎng)的例子這是最簡單的vue的使用實(shí)例榨了,本系列從這個(gè)實(shí)例作為開始來一步一步解析vue2的源碼。本篇就先對Vue構(gòu)造函數(shù)做了一個(gè)簡單的解析攘蔽。
分析
分析項(xiàng)目結(jié)構(gòu)
這個(gè)項(xiàng)目結(jié)構(gòu)我以后每一篇都會(huì)把那一篇需要的都會(huì)再說一遍龙屉,所以不用急著一步到位的了解所有文件夾的用處。
├── src ----------------------------------- 這個(gè)是我們最應(yīng)該關(guān)注的目錄满俗,包含了源碼
│ ├── entries --------------------------- 包含了不同的構(gòu)建或包的入口文件
│ │ ├── web-runtime.js
│ │ ├── web-runtime-with-compiler.js
│ │ ├── web-compiler.js
│ │ ├── web-server-renderer.js
│ ├── compiler
│ │ ├── parser ------------------------ 存放將模板字符串轉(zhuǎn)換成元素抽象語法樹的代碼
│ │ ├── codegen ----------------------- 存放從抽象語法樹(AST)生成render函數(shù)的代碼
│ │ ├── optimizer.js ------------------ 分析靜態(tài)樹转捕,優(yōu)化vdom渲染
│ ├── core ------------------------------ 存放通用的,平臺(tái)無關(guān)的代碼
│ │ ├── observer
│ │ ├── vdom
│ │ ├── instance ---------------------- 包含Vue構(gòu)造函數(shù)設(shè)計(jì)相關(guān)的代碼
│ │ ├── global-api -------------------- 包含給Vue構(gòu)造函數(shù)掛載全局方法(靜態(tài)方法)或?qū)傩缘拇a
│ │ ├── components
│ ├── server
│ ├── platforms
│ ├── sfc
│ ├── shared
Vue構(gòu)造函數(shù)
我們先去找找Vue構(gòu)造函數(shù)在哪吧唆垃,之前的項(xiàng)目結(jié)構(gòu)里面我們也可以看到core文件夾有個(gè)instance文件夾五芝。這里面就是構(gòu)造函數(shù)的定義。
看看index.js的代碼
index.js
import { initMixin } from './init'
import { stateMixin } from './state'
import { renderMixin } from './render'
import { eventsMixin } from './events'
import { lifecycleMixin } from './lifecycle'
import { warn } from '../util/index'
function Vue (options) {
if (process.env.NODE_ENV !== 'production' &&
!(this instanceof Vue)
) {
warn('Vue is a constructor and should be called with the `new` keyword')
}
this._init(options)
}
initMixin(Vue)
stateMixin(Vue)
eventsMixin(Vue)
lifecycleMixin(Vue)
renderMixin(Vue)
export default Vue
這里有個(gè)值得一提的地方辕万,我們看到Vue構(gòu)造函數(shù)里面有一句warn('Vue is a constructor and should be called with the 'new' keyword')
這里開篇我們就不細(xì)看了枢步,這里主要是為了檢測是不是使用的構(gòu)造函數(shù)方式還是直接以函數(shù)的方式調(diào)用的。
然后options被傳進(jìn)了Vue原型里面的_init方法里面渐尿。options回顧一下就是之前的
init.js
這個(gè)文件里面主要內(nèi)容是為Vue原型掛載_init方法
init方法里面的proxy還有內(nèi)部主鍵啥的我們都先不管醉途,看看下面這部分代碼
...
// expose real self
vm._self = vm
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')
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
vm._name = formatComponentName(vm, false)
mark(endTag)
measure(`${vm._name} init`, startTag, endTag)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
...
現(xiàn)在大家可以回憶一下vue文檔里面關(guān)于生命周期那一部分的圖
基本上上面這段代碼涵蓋了new Vue()一直到created鉤子后判斷options里面是否有el屬性。
我們一句一句看砖茸。
initLifecycle
lifecycle.js里面的其中一個(gè)函數(shù)隘擎,基本上是初始化生命周期的一些變量,refs也是這個(gè)階段初始化的凉夯,這個(gè)我們后面會(huì)有一章單獨(dú)講生命周期货葬。
export function initLifecycle (vm: Component) {
const options = vm.$options
// locate first non-abstract parent
let parent = options.parent
if (parent && !options.abstract) {
while (parent.$options.abstract && parent.$parent) {
parent = parent.$parent
}
parent.$children.push(vm)
}
vm.$parent = parent
vm.$root = parent ? parent.$root : vm
vm.$children = []
vm.$refs = {}
vm._watcher = null
vm._inactive = null
vm._directInactive = false
vm._isMounted = false
vm._isDestroyed = false
vm._isBeingDestroyed = false
}
initEvents
event.js其中一個(gè)函數(shù),暫時(shí)我還沒讀完這一部分的代碼劲够,不是很懂具體是干什么的震桶,我系列寫完會(huì)回來重新補(bǔ)充的。
export function initEvents (vm: Component) {
vm._events = Object.create(null)
vm._hasHookEvent = false
// init parent attached events
const listeners = vm.$options._parentListeners
if (listeners) {
updateComponentListeners(vm, listeners)
}
}
這里有一個(gè)值得一提的地方征绎,看到vm._events = Object.create(null)
蹲姐,我們控制臺(tái)可以輸入一下看一下Object.create(null)
結(jié)果是什么。
我一開始有點(diǎn)疑惑炒瘸,這和對象字面量有啥區(qū)別淤堵,不過我又試了下知道了
我也google了一下寝衫,stackoverflow里面也有人問了類似的問題顷扩。Creating Js object with Object.create(null)? 反正這個(gè)方式創(chuàng)建的對象以null為原型創(chuàng)建一個(gè)對象,沒有任何屬性慰毅。
然而typeof null為object隘截,可null又不可能是個(gè)對象,也沒proto指針,很神奇的東西婶芭。
initRender
render.js中的一個(gè)函數(shù),$slots在這里初始化的东臀,還有一些我沒看懂,后面補(bǔ)充犀农。
export function initRender (vm: Component) {
vm._vnode = null // the root of the child tree
vm._staticTrees = null
const parentVnode = vm.$vnode = vm.$options._parentVnode // the placeholder node in parent tree
const renderContext = parentVnode && parentVnode.context
vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext)
vm.$scopedSlots = emptyObject
// bind the createElement fn to this instance
// so that we get proper render context inside it.
// args order: tag, data, children, normalizationType, alwaysNormalize
// internal version is used by render functions compiled from templates
vm._c = (a, b, c, d) => createElement(vm, a, b, c, d, false)
// normalization is always applied for the public version, used in
// user-written render functions.
vm.$createElement = (a, b, c, d) => createElement(vm, a, b, c, d, true)
// $attrs & $listeners are exposed for easier HOC creation.
// they need to be reactive so that HOCs using them are always updated
const parentData = parentVnode && parentVnode.data
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive(vm, '$attrs', parentData && parentData.attrs, () => {
!isUpdatingChildComponent && warn(`$attrs is readonly.`, vm)
}, true)
defineReactive(vm, '$listeners', vm.$options._parentListeners, () => {
!isUpdatingChildComponent && warn(`$listeners is readonly.`, vm)
}, true)
} else {
defineReactive(vm, '$attrs', parentData && parentData.attrs, null, true)
defineReactive(vm, '$listeners', vm.$options._parentListeners, null, true)
}
}
initInjections
inject.js的一個(gè)函數(shù)惰赋,這個(gè)我也沒看,后面補(bǔ)充呵哨。赁濒。。
export function initInjections (vm: Component) {
const result = resolveInject(vm.$options.inject, vm)
if (result) {
observerState.shouldConvert = false
Object.keys(result).forEach(key => {
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
defineReactive(vm, key, result[key], () => {
warn(
`Avoid mutating an injected value directly since the changes will be ` +
`overwritten whenever the provided component re-renders. ` +
`injection being mutated: "${key}"`,
vm
)
})
} else {
defineReactive(vm, key, result[key])
}
})
observerState.shouldConvert = true
}
}
initState
state.js的一個(gè)函數(shù)孟害,可以看到props,methods,data,computed,watch都是這個(gè)時(shí)候初始化的拒炎。
export function initState (vm: Component) {
vm._watchers = []
const opts = vm.$options
if (opts.props) initProps(vm, opts.props)
if (opts.methods) initMethods(vm, opts.methods)
if (opts.data) {
initData(vm)
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
initProvide
也是inject.js里面的一個(gè)函數(shù),這個(gè)也后面補(bǔ)充吧挨务。击你。
export function initProvide (vm: Component) {
const provide = vm.$options.provide
if (provide) {
vm._provided = typeof provide === 'function'
? provide.call(vm)
: provide
}
}
后記
第一章還是只是介紹Vue構(gòu)造函數(shù)并說了比較簡單的東西,沒深入谎柄,下一節(jié)講一下vue的生命周期鉤子實(shí)現(xiàn)丁侄。