在前兩篇文章中,我分別介紹了Vue的構建流程
和Vue入口文件
。有了這些前期的準備工做,下面我將帶你們正式深刻源碼學習。javascript
Vue
的一個核心思想是數據驅動
,相信你們必定對這個不陌生。所謂數據驅動,就是視圖由數據驅動生成。相比傳統的使用jQuery
等前端庫直接操做DOM
,大大提升了開發效率,代碼簡潔易維護。html
在接下來的幾篇文章中,我將主要分享數據驅動
部分相關的源碼解讀。前端
先來看一個簡單的例子:vue
<div id="app">
{{ message }}
</div>
<script>
var app = new Vue({
el: '#app',
data() {
return {
message: 'hello Vue!'
}
}
})
</script>
複製代碼
最終頁面展現效果是: java
如上圖所示,頁面上顯示hello Vue!
,也就是說Vue
將js
裏的數據渲染到DOM
上,也就是數據驅動視圖
,這個渲染過程就是最近幾篇文章咱們要着重分析的。web
本篇文章,咱們先來一塊兒看下new Vue
發生了什麼。app
在上一篇文章中,咱們介紹了Vue構造函數
是定義在src/core/instance/index.js
中的:編輯器
// src/core/instance/index.js
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)
}
複製代碼
構造函數的核心是調用了_init
方法,_init
定義在src/core/instance/init.js
中:ide
// src/core/instance/init.js
Vue.prototype._init = function (options?: Object) {
const vm: Component = this
// a uid
vm._uid = uid++
[1]
let startTag, endTag
/* istanbul ignore if */
if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
startTag = `vue-perf-start:${vm._uid}`
endTag = `vue-perf-end:${vm._uid}`
mark(startTag)
}
// a flag to avoid this being observed
vm._isVue = true
// merge options
if (options && options._isComponent) {
// optimize internal component instantiation
// since dynamic options merging is pretty slow, and none of the
// internal component options needs special treatment.
initInternalComponent(vm, options)
} else {
vm.$options = mergeOptions(
resolveConstructorOptions(vm.constructor),
options || {},
vm
)
}
/* istanbul ignore else */
if (process.env.NODE_ENV !== 'production') {
initProxy(vm)
} else {
vm._renderProxy = vm
}
// 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')
[2]
/* 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)
}
}
複製代碼
梳理下這裏面的執行流程:函數
[1]
和[2]
之間的代碼主要是進行了性能追蹤
,參考官網:
接下來是一個合併options
的操做。
接下來調用了不少初始化函數,從函數名稱能夠看出分別是執行初始化生命週期、初始化事件中心、初始化渲染等操做。文章開頭的 demo 中有定義data
選項,咱們先來分析下initState
是如何處理data
的:
// src/core/instance/state.js
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)
}
}
複製代碼
能夠看到,initState
函數是對props
、methods
、data
、computed
、watch
這幾項的處理。咱們如今只關注initData
對data
的初始化:
// src/core/instance/state.js
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 */)
}
複製代碼
這裏給實例添加了屬性_data
並把data
賦值給它,而後判斷data
若是是一個函數的話會檢查函數返回值是否是純對象,若是不是會拋出警告。
咱們知道,在Vue
中,data
屬性名和methods
中的函數名、props
的屬性名都不能重名,這就是接下來的代碼所作的工做了。這裏遍歷了data
的全部屬性,去和methods
和props
中的進行對比,若是有重名則會拋出警告。若是沒有重名而且isReserved
返回 false 的話,就接着執行proxy
方法。下面是proxy
部分的代碼:
// src/core/instance/state.js
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
export function proxy (target: Object, sourceKey: string, key: string) {
sharedPropertyDefinition.get = function proxyGetter () {
return this[sourceKey][key]
}
sharedPropertyDefinition.set = function proxySetter (val) {
this[sourceKey][key] = val
}
Object.defineProperty(target, key, sharedPropertyDefinition)
}
複製代碼
這裏實際上是作了一層代理,先是定義一個屬性描述符sharedPropertyDefinition
,而後調用Object.defineProperty
,意思就是當訪問/修改target.key
時會觸發get/set
,代理到this[sourceKey][key]
(即vm[_data][key]
)上。
先來看一下,平時咱們是怎麼寫Vue
的:
<script >
export default {
data() {
return {
name: '森林'
}
},
methods: {
print() {
console.log(this.name);
}
}
}
</script>
複製代碼
在methods
中經過this.name
就能直接訪問到data
裏面的值(其實是訪問了this._data.name
)。到這裏,咱們就清楚了爲何在initData
一開始的代碼,開頭有一行是將data
保存到vm._data
中。
回到initData
中,接着上面的繼續往下走,最後就是調用observe
對數據作了響應式處理。響應式處理
部分比較重要,我會在後面的章節中詳細分析。
看完initData
,咱們回到_init
函數。通過一系列的初始化操做後,最後一步是判斷vm.$options.el
是否存在,也即傳入的對象是否有el
屬性,有的話就調用vm.$mount
進行掛載,掛載的目標就是把模板渲染成最終的DOM
。
經過本篇文章,咱們知道了執行new Vue
後實際上是執行_init
進行了一系列初始化的操做。本文呢,咱們是把_init
函數大體的執行流程梳理了一遍。上文也提到函數的最後調用了vm.$mount
進行掛載,這一步操做是數據渲染到DOM
上的關鍵,在下一篇中,我會帶你們一塊兒看下$mount
內部具體進行了什麼操做。