<template>
<div>
<div v-for="item in list2">{{item.name}}{{item.title}}</div>
<button @click="change">按鈕</button>
</div></template><script type="text/ecmascript-6">export default {
data() { return { list1: { name: "John", id: 1 }, list2: [],
};
},
created() { this.obj = this.list1 //Object.assign(this.obj,{title:'123'}) //←直接綁定到obj上不會(huì)給title綁定get和set所以點(diǎn)擊按鈕也不會(huì)更新視圖
//↓創(chuàng)建一個(gè)新的對(duì)象title就能成功綁定get和set~這是什么原理,求解惑
this.obj = Object.assign({},this.obj,{title:'123'})
console.log(this.obj); this.list2.push(this.obj) console.log(this.list2);
}, methods: {
change(){ this.list2[0].title='harry'
}
}
};</script>我的理解是vue會(huì)直接給新聲明對(duì)象的所有屬性自動(dòng)綁定set和get~Object.assign把對(duì)象合并到新對(duì)象上,相當(dāng)于把合并對(duì)象的所有屬性重新聲明到新對(duì)象上所以自動(dòng)綁了get和set,不知道有沒(méi)有理解錯(cuò)~
2 回答

繁花如伊
TA貢獻(xiàn)2012條經(jīng)驗(yàn) 獲得超12個(gè)贊
這個(gè)和vue的observe實(shí)現(xiàn)源碼有關(guān)了,會(huì)觀察對(duì)象有沒(méi)有__ob__屬性,如果有就不會(huì)再去new Observer,如果沒(méi)有就會(huì)去new Observer, Object.assig不會(huì)拷貝__ob__(不可枚舉的)這個(gè)屬性
相關(guān)vue源碼如下
/** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe(value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; // 檢查是否有__ob__屬性 if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob }
/** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer(value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; // 添加__ob__屬性 def(value, '__ob__', this); if (Array.isArray(value)) { if (hasProto) { protoAugment(value, arrayMethods); } else { copyAugment(value, arrayMethods, arrayKeys); } this.observeArray(value); } else { this.walk(value); } };
- 2 回答
- 0 關(guān)注
- 442 瀏覽
添加回答
舉報(bào)
0/150
提交
取消