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.
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) } })
By querying the ECMA document, we learned that the result of the in operator is read through a HasProperty method
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
.
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)
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!