Home  >  Q&A  >  body text

Vue 3 composition api - computed property returns undefined

Using the Vue 3 composition API, how to return the calculated value of the property firstDigit? The keyword this in the computed property is undefined but when I exclude this I get the error fourDigits is not Defined .

<script setup>
import { computed, reactive } from 'vue'

const input = reactive({
    fourDigits: Array(1,2,3,4),
    firstDigit: computed(() => {
      return this.fourDigits[0] <===== `this` is undefined but if I leave `this` out, then `fourDigits` is undefined.
    })
</script>

<template>
   <div>
     <pre>
       {{JSON.stringify(input.firstDigit, null, 2)}}
     </pre>
   </div>
</template>


P粉662089521P粉662089521354 days ago580

reply all(2)I'll reply

  • P粉557957970

    P粉5579579702023-11-01 14:49:47

    If I need to use a state property to assign a value to another state property, I can do this in the onMounted() hook. like this:

    <script setup>
    import { computed, reactive } from 'vue'
    
    const input = reactive({
        fourDigits: Array(1, 2, 3, 4),
        firstDigit: computed(() => {
            return 0; // just some default value
        })
    });
    
    onMounted(() => {
        input.firstDigit = input.fourDigits[0];
    })
    </script>
    
    <template>
       <div>
         <pre>
           {{ JSON.stringify(input.firstDigit, null, 2) }}
         </pre>
       </div>
    </template>
    

    Check if it works for you. wish all the best!

    reply
    0
  • P粉611456309

    P粉6114563092023-11-01 14:49:14

    this is something else in the composition API, try using:

    firstDigit: computed(() => {
      return input.fourDigits[0] 
    })

    reply
    0
  • Cancelreply