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

How to access data in Vue3 reactive proxy object?

王林
Release: 2023-05-10 09:31:07
forward
816 people have browsed it

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 //循环遍历数组
Copy after login

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)
    }
})
Copy after login

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)
  }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template