Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vue2.0响应式原理中Object.defineProperty有什么缺陷?为什么在Vue3.0采用了Proxy? #34

Open
GGXXMM opened this issue Aug 12, 2019 · 0 comments
Labels

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 12, 2019

Object.defineProperty有什么缺陷?

Object.defineProperty()方法只能劫持对象的属性,无法监控数组下标的变化,当数组添加/删除元素不能实时响应。

var arr = [1,2,3,4]
arr.forEach((item,index)=>{
    Object.defineProperty(arr,index,{
        set:function(val){
            console.log('set')
            item = val
        },
        get:function(val){
            console.log('get')
            return item
        }
    })
})
arr[1]; // get  2
arr[1] = 1; // set  1
arr.push(5);// 5(set函数未触发)

为什么在Vue3.0采用了Proxy?

Proxy可以劫持整个对象,并返回一个新的对象。Proxy不仅可以劫持对象,还可以监听数组,高效地监听数据的变化。

var arr = [1, 2, 3, 4];

// 监听数组
var  newArr = new Proxy(arr, {
  get: function(target, key, receiver) {
    console.log(key);
    return Reflect.get(target, key, receiver);
  },
  set: function(target, key, value, receiver) {
    console.log(target, key, value, receiver);
    if (key !== 'length') {
      Render.change(value);
    }
    return Reflect.set(target, key, value, receiver);
  }
});
arr.push(5);
console.log(newArr);// Proxy {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
@GGXXMM GGXXMM added the vue label Dec 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant