Search code examples
javascriptarraysvue.jsvue-composition-api

Vue 3 (composition API) get array length


I'm learning javascript and vue.js 3 composition API. My question is I simply want to get an array length and render at

. The array name : "getForms"

<script>.....
const forms_length = computed(() =>  getForms.value.length)

<template>....
<p> {{form_length}} </p>

I get an error "Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')"

why? and what I should do?

Thank you for your help!


Solution

  • You should use the computed property this way

    <template>
      <p>Array length: {{ formsLength}}</p>
    </template>
    <script>
      import { computed } from 'vue'
      import {useFormsStore} from '../store/forms'
      setup() {
        const { store } = useFormsStore()
        // if the store.forms array is undefined or not ready,
        // then it returns an empty array
        const getForms = computed(() => { return store.forms || []})
        const formsLength = computed(() => getForms.value.length)
    
        return {
          formsLength
        }
      }
    </script>