Vue源码分析之this.message 为什么能访问到 data.message
首先我们需要知道 new Vue 背后发生了哪些事情。
我们都知道,new 关键字在 Javascript 语言中代表实例化是一个对象,而 Vue 实际上是一个类,类在 Javascript 中是用 Function 来实现的,来看一下 vue 方法,在src/core/instance/index.js 中。
1 | function Vue (options) { |
阅读 vue 方法可以知道 Vue 只能通过 new 关键字初始化,然后会调用 this._init 方法, 该方法在同级目录 init.js 中通过 initMixin 方法定义到 vue 原型。
1 | export function initMixin (Vue: Class<Component>) { |
这里 _init 初始化主要就干了几件事情,合并配置,初始化生命周期,初始化事件中心,初始化渲染,初始化 data、props、computed、watcher 等等。这里我们来看下 initState 方法:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15export 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)
}
}
阅读代码可以知道 此处判断 new Vue 中是否有定义 props,methods,data,若有 分别执行 初始化函数。这里我们看一下 initData 是如何初始化 data。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41function 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 */)
}
我们知道 vue 里面 data 是以一个 function 的形式存在的,通过阅读这里的代码,可以看见如果 data 是 function,通过 getData 方法 call 了一下,然后 判断 是否有重复, 没有就执行proxy方法:1
2
3
4
5
6
7
8
9export 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)
}
阅读代码我们可以知道,在访问 this.message 时,实质上是通过此方法代理后访问到 this._data.message。