Home  >  Article  >  Web Front-end  >  How to access data in Vue3 reactive proxy object?

How to access data in Vue3 reactive proxy object?

王林
王林forward
2023-05-10 09:31:07742browse

Text

In vue, obj.a is a read operation, but if you think about it carefully, the read operation is very broad.

obj.a // 访问一个属性
'a' in obj // 判断对象或者原型链上是否存在a
for ... in //循环遍历对象
for ... of //循环遍历数组

There is no for...of in the book, but I think this should also be a read operation, and its internal implementation in js should probably be the same as for.. .in is very similar.

Read attributes

In fact, we have already implemented this before, which is to intercept the Get operation through Proxy. As for why we need to use Reflect

const obj = {a:1}
const p = new Proxy(obj,{
    get(target,key,receiver){
        track(target,key)
        return Reflect.get(target,key,receiver)
    }
})

xx in obj

By querying the ECMA document, we learned that the result of the in operator is read through a HasProperty method

How to access data in Vue3 reactive proxy object?

and This method corresponds to the has method inside Proxy.

So we only need to add has interception. Colleagues also have the has method for Reflect.

for ... in

This will be a little more complicated than the previous one. By querying the ECMA document, in this article, it is specified how to convert an object into an iterator, written here After a demo, we can clearly find that it traverses Reflect.ownKeys(obj)

How to access data in Vue3 reactive proxy object?

const ITERATE_KEY=symbol()
const p = new Proxy(obj,{
 ownKeys(target){
        track(target,ITERATE_KEY)
        return Reflect.ownKeys(target)
  }
}

The above is the detailed content of How to access data in Vue3 reactive proxy object?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete