使用Vue.$set()或者Object.assign()修改對象新增響應(yīng)式屬性的方法
首先建議先讀讀Vue官方文檔深入響應(yīng)式原理
的介紹,對這一塊你的理解會加深很多
深入響應(yīng)式原理
vue代碼中,只要在data對象里定義的對象,賦值后,任意一個屬性值發(fā)生變化
,視圖都會實時變化
比如下面在data定義了obj對象,mounted里賦值后,(也可以在其他地方賦值)只要obj.a
或者obj.b
的值改變了,視圖會跟著變化
data() { return { obj: {} } }, mounted: { this.obj = {a:1, b: 2} // 改變this.obj.a this.obj.c的值視圖會更新 this.obj.c = 3 // 改變this.obj.c的值 視圖不會更新 Object.assign(this.obj, {d: 4}) // 改變this.obj.c的值 視圖不會更新 this.$set(this.obj, 'e', 5) // 改百年this.obj.e時 視圖會更新 console.log('obj' + this.obj) }
但是我們在obj對象上新增的屬性
變化時,值會變化,但是視圖不會實時變化
比如obj.c
或者obj.d
變化時,值雖然會變,但是視圖不會跟著變
Vue.$set()
使用Vue.$set()
方法,既可以新增屬性
,又可以觸發(fā)視圖更新
,比如obj.e
改變時,視圖會相應(yīng)改變
打印出的obj,可以看出,新增的屬性只有通過this.set()的obj.e屬性有g(shù)et和set方法的,而新增的obj.c和obj.d沒有
根據(jù)官方文檔定義:如果在實例創(chuàng)建之后添加新的屬性到實例上,它不會觸發(fā)視圖更新。
當(dāng)我們把一個JavaScript 對象傳入 Vue 實例作為 data 選項,Vue 將遍歷此對象所有的屬性,并使用 Object.defineProperty把這些屬性全部轉(zhuǎn)為 getter/setter。
Vue.$set()源碼
Vue2.6.12版本的源碼
/** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ export function set (target: Array<any> | Object, key: any, val: any): any { if (process.env.NODE_ENV !== 'production' && (isUndef(target) || isPrimitive(target)) ) { warn(`Cannot set reactive property on undefined, null, or primitive value: ${(target: any)}`) } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key) target.splice(key, 1, val) return val } if (key in target && !(key in Object.prototype)) { target[key] = val return val } const ob = (target: any).__ob__ if (target._isVue || (ob && ob.vmCount)) { process.env.NODE_ENV !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ) return val } if (!ob) { target[key] = val return val } defineReactive(ob.value, key, val) ob.dep.notify() return val }
/** * Define a reactive property on an Object. */ export function defineReactive ( obj: Object, key: string, val: any, customSetter?: ?Function, shallow?: boolean ) { 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) { 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) { 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) dep.notify() } }) }
Object.assign()
給data定義的對象新增屬性
,同時又要視圖實時更新
,除了用Vue.$set()
方法,也可以通過Object.assign()
實現(xiàn)
data() { return { obj: {} } }, mounted: { this.obj = { a: 1, b: 2 } this.obj.c = 3 Object.assign(this.obj, { d: 4 }) // this.$set(this.obj, 'e', 5) // 下面這一行代碼才觸發(fā)了視圖更新 this.obj = Object.assign({}, this.obj, {e: 5}) console.log("obj", this.obj) }
以上的代碼等同于
data() { return { obj: {} } }, mounted: { this.obj = { a: 1, b: 2, c: 3, d: 4, e: 5 } }
$set()方法不生效時,改用Object.assign()試試
今天一美女同事
使用this.$set()
去改變一個傳入組件的對象(沒有直接定義在data對象中,通過mixins選項做相關(guān)操作,能夠通過this.去獲取)
,沒有觸發(fā)視圖更新
而改用Object.assign()
去給對象重新賦值時,會觸發(fā)視圖更新
通過重新給對象賦值
,來使視圖更新;
使用Object.assign()新增,或者改變原有對象,
// 起作用的是給對象重新賦值 this.obj = Object.assign({}, this.obj, {e: 5})
到此這篇關(guān)于使用Vue.$set()或者Object.assign()修改對象新增響應(yīng)式屬性的文章就介紹到這了,更多相關(guān)Vue.$set()響應(yīng)式屬性內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue完美實現(xiàn)el-table列寬自適應(yīng)
這篇文章主要介紹了vue完美實現(xiàn)el-table列寬自適應(yīng),對vue感興趣的同學(xué),可以參考下2021-05-05前端vue如何根據(jù)菜單自動生成路由(動態(tài)配置前端路由)
估計有不少人遇過這樣的需求:根據(jù)后臺數(shù)據(jù)動態(tài)添加路由和菜單,這篇文章主要給大家介紹了關(guān)于前端vue如何根據(jù)菜單自動生成路由的相關(guān)資料,需要的朋友可以參考下2024-04-04解決vuex數(shù)據(jù)異步造成初始化的時候沒值報錯問題
今天小編大家分享一篇解決vuex數(shù)據(jù)異步造成初始化的時候沒值報錯問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11vue項目中頁面底部出現(xiàn)白邊及空白區(qū)域錯誤的問題
這篇文章主要介紹了vue項目中頁面底部出現(xiàn)白邊及空白區(qū)域錯誤的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08