I have a computed value emptyRowsRemoved
derived from the Reactivity API. I need to iterate over this value. But because computed()
returns a proxy, I am no longer able to iterate over it with a .forEach
.
I was curious, is the only way to iterate over the proxy is to unRef
the value? It seems there should be some way to iterate over a proxy. I searched for this but I cannot find an answer to this question.
CodePudding user response:
computed()
doesn't return a Proxy
. Rather it returns a ref
, whose value
property contains the target data.
I was curious, is the only way to iterate over the proxy is to unRef the value?
Indeed, you do need to unwrap the ref
with unref()
, or just directly reference its .value
property to access the target array data (unless using the new Reactivity Transform described below).
Assuming your usage includes a computed()
whose value is a Proxy
somehow, such as in this contrived example:
const myComputedProxy = computed(() => proxyOf(/* my array */))
...the Proxy
itself should be treated exactly like the target variable. If the Proxy
is for an array, use the Proxy
directly as if it were the array itself. That is, you can use .forEach()
on the Proxy
, which will forward the call to the underlying Array
:
myComputedProxy.value.forEach(x => console.log(x))
// or
import { unref } from 'vue'
unref(myComputedProxy).forEach(x => console.log(x))
Using Reactivity Transform
However, Vue 3's Reactivity Transform (experimental as of [email protected]
) avoids the requirement of unwrapping the ref
, but you must use a <script setup>
block (instead of setup()
in the Options API). Instead of importing computed
(or ref
) from vue
, use the globally defined $computed
(or $ref
) compiler macros:
<script setup>