vue初始化数据
var app = new Vue({
data() {
return {
msg: 'hello,weekend!',
name: 'YanHSama'
}
},
mounted() {
console.log('vue', this);
},
watch: {
},
computed: {
},
methods: {
},
})
// mount
app.$mount('#testdata')
proxy代理
数据代理
在Vue初始化时,执行_init
方法,_init
函数汇总会执行initData
方法
function initData (vm: Component) {
let data = vm.$options.data
//赋值vm._data
data = vm._data = typeof data === 'function'? getData(data, vm) : 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]
if (props && hasOwn(props, key)) {
//给出警告,data存在key与props的key同名
} else if (!isReserved(key)) {
// 当key 不已$ or _开头,进行代理
proxy(vm, `_data`, key)
}
}
// observe data
//对数据进行观测 --响应式数据核心
observe(data, true /* asRootData */)
}
//执行data方法
export function getData (data: Function, vm: Component): any {
//加入栈
pushTarget()
try {
//执行data方法,this指向vm
return data.call(vm, vm)
} catch (e) {
handleError(e, vm, `data()`)
return {}
} finally {
//移除栈
popTarget()
}
}
Dep.target = null
const targetStack = []
export function pushTarget (target: ?Watcher) {
targetStack.push(target)
Dep.target = target
}
export function popTarget () {
targetStack.pop()
Dep.target = targetStack[targetStack.length - 1]
}
代理
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)
}
const sharedPropertyDefinition = {
enumerable: true,
configurable: true,
get: noop,
set: noop
}
export function observe (value: any, asRootData: ?boolean): Observer | void {
//判断是否对象或者是否vnode,如果不是不做检测
if (!isObject(value) || value instanceof VNode) {
return
}
let ob: Observer | void
//判断value是否含有__ob__属性,这是标明是否已经被检测的标志
if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) {
ob = value.__ob__
} else if (
//shouldObserve默认值为true
shouldObserve &&
//是否服务端渲染
!isServerRendering() &&
//是否数组,是否对象,是否可扩展
(Array.isArray(value) || isPlainObject(value)) &&
Object.isExtensible(value) &&
!value._isVue
) {
ob = new Observer(value)
}
if (asRootData && ob) {
ob.vmCount++
}
return ob
}
Observer类
export class Observer {
value: any;
dep: Dep;
vmCount: number; // number of vms that has this object as root $data
constructor (value: any) {
// this为Observe
this.value = value
this.dep = new Dep()
this.vmCount = 0
//给value新增一个__ob__属性,值为该value的Observer实例,相当于为value打上标记,表示它已经被转化成响应式了,避免重复操作
def(value, '__ob__', this)
//判断是否数组
if (Array.isArray(value)) {
const augment = hasProto ? protoAugment : copyAugment
augment(value, arrayMethods, arrayKeys)
this.observeArray(value)
} else {
//只有object类型的数据才会调用walk将每一个属性转换成getter/setter的形式来侦测变化
this.walk(value)
}
}
/**
* Walk through each property and convert them into
* getter/setters. This method should only be called when
* value type is Object.
*/
walk (obj: Object) {
const keys = Object.keys(obj)
for (let i = 0; i < keys.length; i++) {
defineReactive(obj, keys[i], obj[keys[i]])
}
}
/**
* Observe a list of Array items.
*/
observeArray (items: Array<any>) {
for (let i = 0, l = items.length; i < l; i++) {
// 对数组数据类型进行深层观测
observe(items[i])
}
}
}
export function defineReactive (
obj: Object,//obj 对象
key: string,//对象的key
val: any,//对象的某个key的值
customSetter?: ?Function,
shallow?: boolean
) {
//实例化一个依赖管理器,生成一个依赖管理数组dep
const dep = new Dep()
const property = Object.getOwnPropertyDescriptor(obj, key)
if (property && property.configurable === false) {
return
}
// cater for pre-defined getter/setters
const getter = property && property.get
const setter = property && property.set
if ((!getter || setter) && arguments.length === 2) {
//如果只传了obj和key,那么val = obj[key]
val = obj[key]
}
let childOb = !shallow && observe(val)
Object.defineProperty(obj, key, {
enumerable: true,
configurable: true,
get: function reactiveGetter () {
const value = getter ? getter.call(obj) : val
if (Dep.target) {
在getter中收集依赖
dep.depend()
if (childOb) {
childOb.dep.depend()
if (Array.isArray(value)) {
dependArray(value)
}
}
}
return value
},
set: function reactiveSetter (newVal) {
const value = getter ? getter.call(obj) : val
/* eslint-disable no-self-compare */
if (newVal === value || (newVal !== newVal && value !== value)) {
return
}
/* eslint-enable no-self-compare */
if (process.env.NODE_ENV !== 'production' && customSetter) {
customSetter()
}
// #7981: for accessor properties without setter
if (getter && !setter) return
if (setter) {
setter.call(obj, newVal)
} else {
val = newVal
}
childOb = !shallow && observe(newVal)
//在setter中通知依赖更新
dep.notify()
}
})
}
Dep类
export default class Dep {
static target: ?Watcher;
id: number;
subs: Array<Watcher>;
constructor () {
this.id = uid++
//初始化了一个subs数组,用来存放依赖
this.subs = []
}
addSub (sub: Watcher) {
this.subs.push(sub)
}
//移除一个依赖
removeSub (sub: Watcher) {
remove(this.subs, sub)
}
//添加一个依赖
depend () {
if (Dep.target) {
Dep.target.addDep(this)
}
}
// 通知所有依赖更新
notify () {
const subs = this.subs.slice()
for (let i = 0, l = subs.length; i < l; i++) {
subs[i].update()
}
}
}