在 Vue Composition 中迭代代理 API

Iterating over a Proxy in Vue Composition API

我有一个计算值 emptyRowsRemoved 来自反应性 API。我需要迭代这个值。但是因为 computed() returns 代理,我不能再用 .forEach.

迭代它

我很好奇,迭代代理的唯一方法是 unRef 值吗?似乎应该有某种方法可以遍历代理。我搜索了这个,但我找不到这个问题的答案。

computed() 不 return 一个 Proxy. Rather it returns a ref,其 value 属性 包含目标数据。

I was curious, is the only way to iterate over the proxy is to unRef the value?

确实,您确实需要用 unref() 解包 ref,或者直接引用它的 .value 属性 来访问目标数组数据(除非使用新的反应性转换如下所述)。

假设您的用法包括一个 computed(),其值以某种方式为 Proxy,例如在这个人为的示例中:

const myComputedProxy = computed(() => proxyOf(/* my array */))

...Proxy 本身应该像对待目标变量一样对待。如果 Proxy 用于数组,则直接使用 Proxy 就好像它是数组本身一样。也就是说,您可以在 Proxy 上使用 .forEach(),这会将调用转发到基础 Array:

myComputedProxy.value.forEach(x => console.log(x))

// or
import { unref } from 'vue'
unref(myComputedProxy).forEach(x => console.log(x))

demo 1

使用反应性变换

然而,Vue 3 的 Reactivity Transform (experimental as of vue@3.2.26) avoids the requirement of unwrapping the ref, but you must use a <script setup> block(而不是 Options API 中的 setup())。不要从 vue 导入 computed(或 ref),而是使用全局定义的 $computed(或 $ref)编译器宏:

<script setup>          
const myComputedProxy = $computed(() => proxyOf(/* my array */))
myComputedProxy.forEach(x => console.log(x))
</script>

demo 2