Using the Vue 3 composition API, how can I return the computed value for the property, firstDigit
? The keyword, this
, in the computed property is undefined
but when I leave this
out, then 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>
CodePudding user response:
this
is something else in composition API , try with:
firstDigit: computed(() => {
return input.fourDigits[0]
})
CodePudding user response:
If I need to use state property to assign a value to another state property, I do it in 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 will work for you. All the best!