Vue 3 composition api - computed property returns undefined
P粉662089521
P粉662089521 2023-10-31 19:00:10
0
2
642

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粉662089521
P粉662089521

reply all(2)
P粉557957970

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!

P粉611456309

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

firstDigit: computed(() => {
  return input.fourDigits[0] 
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template