先來一段vue代碼
import Vue from 'vue' new Vue({ el: '#app', data: { message: 'hello world' }, mounted() { console.log(this.message) } })
從源碼理解
function Vue (options) { ··· this._init(options) 2、new Vue實例時,執行_init方法 } ··· initMixin(Vue) 1、Vue方法方法創建時,執行initMixin 給原型上綁定了_init方法 ··· ———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————— Vue.prototype._init = function (options?: Object) { const vm: Component = this ··· initState(vm) 3、執行_init方法,執行initState }
_________________________________________________________________________________________________________________________________
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) 4、如果實例化Vue時,data存在,執行initData方法
} else {
observe(vm._data = {}, true /* asRootData */)
}
if (opts.computed) initComputed(vm, opts.computed)
if (opts.watch && opts.watch !== nativeWatch) {
initWatch(vm, opts.watch)
}
}
——————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
function initData (vm: Component) {
let data = vm.$options.data data = vm._data = typeof data === 'function' ? getData(data, vm) : data || {} ···省略代碼 : 如果data不是一個對象,則提示data方法必須返回一個對象··· // 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] ······methods中不能存在和data中相同屬性的一些判斷提示······ if (props && hasOwn(props, key)) { ········props中不能存在和data中相同屬性的一些判斷提示······· } else if (!isReserved(key)) { proxy(vm, `_data`, key) 5、代理,給vm.key 做一層代理,返回實際vm['_data'][key] } } // observe data observe(data, true /* asRootData */) }
———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
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) // 6、訪問vm.key 時 返回了 vm['_data'][key] }
所以在vue中通過this. 方式訪問data中的數據時,實際上是返回了this._data中的數據