接觸vue也有段時(shí)間了,經(jīng)手的項(xiàng)目也有幾個(gè)了,一直沒怎么研究下源碼,趁著沒有加班的日子,參考了幾篇文章的分析后,自己也想看看new Vue的大致過程,加深對(duì)vue的了解,以便于日后更好的編寫vue代碼
我們無論是用官方的腳手架,還是自己搭建的項(xiàng)目模板,最終都會(huì)創(chuàng)建一個(gè)vue的實(shí)例對(duì)象并掛載到指定dom上,我們可以從new Vue()的實(shí)例化過程中,作為vue源碼分析的入口,此篇文章在具體實(shí)現(xiàn)上面不做深入了解,意在淺析vue的大致結(jié)構(gòu),對(duì)new Vue有一個(gè)整體的了解
1. vue入口:new Vue()構(gòu)造函數(shù)
// vue/src/platform/web/entry-runtime.js
/* @flow */
import Vue from './runtime/index'
export default Vue
從vue1到vue2的迭代上,vue采用了flow進(jìn)行靜態(tài)代碼類型檢查
// vue/src/platform/web/runtime/index.js
import Vue from 'core/index'
import config from 'core/config'
import { extend, noop } from 'shared/util'
import { mountComponent } from 'core/instance/lifecycle'
import { devtools, inBrowser, isChrome } from 'core/util/index'
繼續(xù)找到Vue的引用所在地
// vue/src/core/instance/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
2. 構(gòu)造函數(shù)干了什么
到這里,我們可以在上述代碼中看到Vue的構(gòu)造函數(shù),在構(gòu)造函數(shù)中執(zhí)行了_init,隨后執(zhí)行了導(dǎo)入的五大Mixin,進(jìn)行實(shí)例化的初始化過程
initMixin(Vue) // options初始化
stateMixin(Vue) // 狀態(tài)(props、state、computed、watch)
eventsMixin(Vue) // 事件
lifecycleMixin(Vue) // 生命周期
renderMixin(Vue) // 頁面渲染
找到_init執(zhí)行函數(shù)
export function initMixin (Vue: Class<Component>) {
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
...
這個(gè)函數(shù)主要對(duì)我們?cè)趯?shí)例化中的配置與默認(rèn)配置進(jìn)行了合并,并且依次執(zhí)行了以下幾步
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(`vue ${vm._name} init`, startTag, endTag)
}
if (vm.$options.el) {
vm.$mount(vm.$options.el)
}
initLifecycle: 初始化生命周期
initEvents: 初始化事件
initRender: 渲染頁面
callHook(vm, 'beforeCreate'): beforeCreate鉤子函數(shù)
initState:初始化狀態(tài) props data computed watch methods
callHook(vm, 'created'):created鉤子函數(shù)
我們重點(diǎn)關(guān)注下 initState中的 initData,也就是老生常談的數(shù)據(jù)雙向綁定
function initData (vm: Component) {
let data = vm.$options.data
data = vm._data = typeof data === 'function'
? getData(data, vm)
: data || {}
if (!isPlainObject(data)) {
data = {}
process.env.NODE_ENV !== 'production' && warn(
'data functions should return an object:\n' +
'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function',
vm
)
}
// proxy data on instance
const keys = Object.keys(data)
const props = vm.$options.props
const methods = vm.$options.methods
let i = keys.length
while (i--) {
const key = keys[i]
if (process.env.NODE_ENV !== 'production') {
if (methods && hasOwn(methods, key)) {
warn(
`Method "${key}" has already been defined as a data property.`,
vm
)
}
}
if (props && hasOwn(props, key)) {
process.env.NODE_ENV !== 'production' && warn(
`The data property "${key}" is already declared as a prop. ` +
`Use prop default value instead.`,
vm
)
} else if (!isReserved(key)) {
proxy(vm, `_data`, key)
}
}
// observe data
observe(data, true /* asRootData */)
}
在上面的代碼中找到兩個(gè)關(guān)鍵字 proxy 和 observe
前者的作用:
我們?cè)趘ue中調(diào)用數(shù)據(jù): this.demo = 123
但是在源碼初始化的過程中,是這樣的 this._data.demo = 123
proxy就是將key值做了代理,簡化了調(diào)用,方便了我們
后者的作用:
開始進(jìn)行雙向數(shù)據(jù)綁定 observe(data, true /* asRootData */)
簡化后的observe
export function observe (value) {
if (!isObject(value)) {
return
}
let ob = new Observer(value)
return ob
}
export class Observer {
constructor (value) {
this.value = value
this.dep = new Dep()
this.vmCount = 0
def(value, '__ob__', this)
this.walk(value)
}
walk (obj) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i], obj[keys[i]])
}
}
}
export function defineReactive (obj, key, val) {
const dep = new Dep()
let childOb = observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
// 取值時(shí)給數(shù)據(jù)添加依賴
get: function reactiveGetter () {
const value = val
if (Dep.target) {
dep.depend()
if (childOb) {
childOb.dep.depend()
}
}
return value
},
// 賦值時(shí)通知數(shù)據(jù)依賴更新
set: function reactiveSetter (newVal) {
const value = val
if (newVal === value) {
return
}
val = newVal
childOb = observe(newVal)
dep.notify()
}
})
}
這里在簡單闡述下vue雙向數(shù)據(jù)綁定的原理:
發(fā)布者-訂閱者 + 數(shù)據(jù)劫持
在上述的代碼中,重點(diǎn)關(guān)注 defineReactive函數(shù),對(duì)vue對(duì)象中的每個(gè)屬性進(jìn)行了遞歸遍歷的監(jiān)聽,利用 Object.defineProperty對(duì)每個(gè)屬性進(jìn)行監(jiān)聽,在取值的時(shí)候添加依賴進(jìn)行依賴收集,在復(fù)制的時(shí)候進(jìn)行通知訂閱者進(jìn)行依賴更新。
具體的細(xì)節(jié)請(qǐng)參考:https://segmentfault.com/a/1190000006599500