DEV Community

ktr92
ktr92

Posted on • Updated on

[vue3] Why is the length of a reactive Array always undefined?

I once spent a lot of time due to my superficial knowledge of Vue reactivity. I saw it very clearly and simply, but I never really thought about how it works.

For example, we have an empty array of strings that will be filled after user actions.

const inputData = ref<string[]>([])
Enter fullscreen mode Exit fullscreen mode

You'll always use ref() for primitives, but ref() is good for objects that need to be reassigned, like an array.

After the user's action and filling the array, we need to show him some information in the template, but before that it was hidden. So we add a computed property to keep track of the length of the array.

const inputLength = computed(() => {
  return inputData.value.length
})
Enter fullscreen mode Exit fullscreen mode
<template v-if="inputLength ">
 some information
</template>
Enter fullscreen mode Exit fullscreen mode

Problem:
At first glance this seems correct (to me), but it doesn't work because since we're using ref, our inputData is not an array of strings, but a ref object that has one property value. And inputData.value is also not an array of strings, but a proxy object.
So our inputLength computed property is always undefined.
For a long time I could not understand what was wrong here.

All we need to do is use Object.keys and get the number of keys of the proxy object.

Solution:

const inputLength = computed(() => {
  return Object.keys(inputData.value).length
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)