Vue3用Proxy替代defineProperty的原因
一、Object.defineProperty
定義:Object.defineProperty() 方法會(huì)直接在一個(gè)對(duì)象上定義一個(gè)新屬性,或者修改一個(gè)對(duì)象的現(xiàn)有屬性,并返回此對(duì)象
1.1 為什么能實(shí)現(xiàn)響應(yīng)式
通過defineProperty 兩個(gè)屬性,get及set
get
屬性的 getter 函數(shù),當(dāng)訪問該屬性時(shí),會(huì)調(diào)用此函數(shù)。執(zhí)行時(shí)不傳入任何參數(shù),但是會(huì)傳入 this 對(duì)象(由于繼承關(guān)系,這里的this并不一定是定義該屬性的對(duì)象)。該函數(shù)的返回值會(huì)被用作屬性的值
set
屬性的 setter 函數(shù),當(dāng)屬性值被修改時(shí),會(huì)調(diào)用此函數(shù)。該方法接受一個(gè)參數(shù)(也就是被賦予的新值),會(huì)傳入賦值時(shí)的 this 對(duì)象。默認(rèn)為 undefined
下面通過代碼展示:
定義一個(gè)響應(yīng)式函數(shù)defineReactive
function update() {
app.innerText = obj.foo
}
function defineReactive(obj, key, val) {
Object.defineProperty(obj, key, {
get() {
console.log(`get ${key}:${val}`);
return val
},
set(newVal) {
if (newVal !== val) {
val = newVal
update()
}
}
})
}
調(diào)用defineReactive,數(shù)據(jù)發(fā)生變化觸發(fā)update方法,實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式
const obj = {}
defineReactive(obj, 'foo', '')
setTimeout(()=>{
obj.foo = new Date().toLocaleTimeString()
},1000)
在對(duì)象存在多個(gè)key情況下,需要進(jìn)行遍歷
function observe(obj) {
if (typeof obj !== 'object' || obj == null) {
return
}
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
})
}
如果存在嵌套對(duì)象的情況,還需要在defineReactive中進(jìn)行遞歸
function defineReactive(obj, key, val) {
observe(val)
Object.defineProperty(obj, key, {
get() {
console.log(`get ${key}:${val}`);
return val
},
set(newVal) {
if (newVal !== val) {
val = newVal
update()
}
}
})
}
當(dāng)給key賦值為對(duì)象的時(shí)候,還需要在set屬性中進(jìn)行遞歸
set(newVal) {
if (newVal !== val) {
observe(newVal) // 新值是對(duì)象的情況
notifyUpdate()
}
}
上述例子能夠?qū)崿F(xiàn)對(duì)一個(gè)對(duì)象的基本響應(yīng)式,但仍然存在諸多問題
現(xiàn)在對(duì)一個(gè)對(duì)象進(jìn)行刪除與添加屬性操作,無法劫持到
const obj = {
foo: "foo",
bar: "bar"
}
observe(obj)
delete obj.foo // no ok
obj.jar = 'xxx' // no ok
當(dāng)我們對(duì)一個(gè)數(shù)組進(jìn)行監(jiān)聽的時(shí)候,并不那么好使了
const arrData = [1,2,3,4,5];
arrData.forEach((val,index)=>{
defineProperty(arrData,index,val)
})
arrData.push() // no ok
arrData.pop() // no ok
arrDate[0] = 99 // ok
可以看到數(shù)據(jù)的api無法劫持到,從而無法實(shí)現(xiàn)數(shù)據(jù)響應(yīng)式,
所以在Vue2中,增加了set、delete API,并且對(duì)數(shù)組api方法進(jìn)行一個(gè)重寫
還有一個(gè)問題則是,如果存在深層的嵌套對(duì)象關(guān)系,需要深層的進(jìn)行監(jiān)聽,造成了性能的極大問題
1.2 小結(jié)
- 檢測不到對(duì)象屬性的添加和刪除
- 數(shù)組
API方法無法監(jiān)聽到 - 需要對(duì)每個(gè)屬性進(jìn)行遍歷監(jiān)聽,如果嵌套對(duì)象,需要深層監(jiān)聽,造成性能問題
二、proxy
Proxy的監(jiān)聽是針對(duì)一個(gè)對(duì)象的,那么對(duì)這個(gè)對(duì)象的所有操作會(huì)進(jìn)入監(jiān)聽操作,這就完全可以代理所有屬性了
在ES6系列中,我們?cè)敿?xì)講解過Proxy的使用,就不再述說了
下面通過代碼進(jìn)行展示:
定義一個(gè)響應(yīng)式方法reactive
function reactive(obj) {
if (typeof obj !== 'object' && obj != null) {
return obj
}
// Proxy相當(dāng)于在對(duì)象外層加攔截
const observed = new Proxy(obj, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
console.log(`獲取${key}:${res}`)
return res
},
set(target, key, value, receiver) {
const res = Reflect.set(target, key, value, receiver)
console.log(`設(shè)置${key}:${value}`)
return res
},
deleteProperty(target, key) {
const res = Reflect.deleteProperty(target, key)
console.log(`刪除${key}:${res}`)
return res
}
})
return observed
}
測試一下簡單數(shù)據(jù)的操作,發(fā)現(xiàn)都能劫持
const state = reactive({
foo: 'foo'
})
// 1.獲取
state.foo // ok
// 2.設(shè)置已存在屬性
state.foo = 'fooooooo' // ok
// 3.設(shè)置不存在屬性
state.dong = 'dong' // ok
// 4.刪除屬性
delete state.dong // ok
再測試嵌套對(duì)象情況,這時(shí)候發(fā)現(xiàn)就不那么 OK 了
const state = reactive({
bar: { a: 1 }
})
// 設(shè)置嵌套對(duì)象屬性
state.bar.a = 10 // no ok
如果要解決,需要在get之上再進(jìn)行一層代理
function reactive(obj) {
if (typeof obj !== 'object' && obj != null) {
return obj
}
// Proxy相當(dāng)于在對(duì)象外層加攔截
const observed = new Proxy(obj, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
console.log(`獲取${key}:${res}`)
return isObject(res) ? reactive(res) : res
},
return observed
}
三、總結(jié)
Object.defineProperty只能遍歷對(duì)象屬性進(jìn)行劫持
function observe(obj) {
if (typeof obj !== 'object' || obj == null) {
return
}
Object.keys(obj).forEach(key => {
defineReactive(obj, key, obj[key])
})
}
Proxy直接可以劫持整個(gè)對(duì)象,并返回一個(gè)新對(duì)象,我們可以只操作新的對(duì)象達(dá)到響應(yīng)式目的
function reactive(obj) {
if (typeof obj !== 'object' && obj != null) {
return obj
}
// Proxy相當(dāng)于在對(duì)象外層加攔截
const observed = new Proxy(obj, {
get(target, key, receiver) {
const res = Reflect.get(target, key, receiver)
console.log(`獲取${key}:${res}`)
return res
},
set(target, key, value, receiver) {
const res = Reflect.set(target, key, value, receiver)
console.log(`設(shè)置${key}:${value}`)
return res
},
deleteProperty(target, key) {
const res = Reflect.deleteProperty(target, key)
console.log(`刪除${key}:${res}`)
return res
}
})
return observed
}
Proxy可以直接監(jiān)聽數(shù)組的變化(push、shift、splice)
const obj = [1,2,3] const proxtObj = reactive(obj) obj.psuh(4) // ok
Proxy有多達(dá)13種攔截方法,不限于apply、ownKeys、deleteProperty、has等等,這是Object.defineProperty不具備的
正因?yàn)?code>defineProperty自身的缺陷,導(dǎo)致Vue2在實(shí)現(xiàn)響應(yīng)式過程需要實(shí)現(xiàn)其他的方法輔助(如重寫數(shù)組方法、增加額外set、delete方法)
// 數(shù)組重寫
const originalProto = Array.prototype
const arrayProto = Object.create(originalProto)
['push', 'pop', 'shift', 'unshift', 'splice', 'reverse', 'sort'].forEach(method => {
arrayProto[method] = function () {
originalProto[method].apply(this.arguments)
dep.notice()
}
});
// set、delete
Vue.set(obj,'bar','newbar')
Vue.delete(obj),'bar')
Proxy 不兼容IE,也沒有 polyfill, defineProperty 能支持到IE9
到此這篇關(guān)于Vue3用Proxy替代defineProperty的原因的文章就介紹到這了,更多相關(guān)Vue3 Proxy替代defineProperty內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue 2.0學(xué)習(xí)筆記之Vue中的computed屬性
本篇文章主要介紹了Vue 2.0學(xué)習(xí)筆記之Vue中的computed屬性,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
Element-UI日期選擇器(選擇日期范圍)禁用未來日期實(shí)現(xiàn)代碼
我們?cè)诰W(wǎng)頁開發(fā)時(shí)通常需要用到一些日期組件來方便用戶選擇時(shí)間,其中element日期組件是一個(gè)非常好用的工具,這篇文章主要給大家介紹了關(guān)于Element-UI日期選擇器(選擇日期范圍)禁用未來日期的相關(guān)資料,需要的朋友可以參考下2024-02-02
vuex實(shí)現(xiàn)數(shù)據(jù)狀態(tài)持久化
今天小編就為大家分享一篇vuex實(shí)現(xiàn)數(shù)據(jù)狀態(tài)持久化,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-11-11
element-ui?table表格控件實(shí)現(xiàn)單選功能代碼實(shí)例
這篇文章主要給大家介紹了關(guān)于element-ui?table表格控件實(shí)現(xiàn)單選功能的相關(guān)資料,單選框是指在?Element?UI?的表格組件中,可以通過單選框來選擇一行數(shù)據(jù)。用戶只能選擇一行數(shù)據(jù),而不能同時(shí)選擇多行,需要的朋友可以參考下2023-09-09
vue項(xiàng)目下npm或yarn下安裝echarts多個(gè)版本方式
這篇文章主要介紹了vue項(xiàng)目下npm或yarn下安裝echarts多個(gè)版本方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06
vue前端測試開發(fā)watch監(jiān)聽data的數(shù)據(jù)變化
這篇文章主要為大家介紹了vue測試開發(fā)watch監(jiān)聽data的數(shù)據(jù)變化,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05

