Can someone please explain why the Javascript object property, data.test
, always holds the initial value of the computed property, square
? Even after submitting a number in the input field, data.test
remains set to 4. On the other hand, the computed property seems to be working correctly as indicated by the HTML elements, anyNum
and square
.
Check out the code on this fiddle
<script setup>
import { ref, computed } from 'vue'
const anyNum = ref(2)
const square = computed(() => {
return anyNum.value * anyNum.value
})
const data = {
test: square.value <===== JavaScript object property always equals 4
}
function submitForm() {
console.log(data)
}
</script>
<template>
<p>anyNum: {{ anyNum }} </p>
<p>square: {{square}} </p>
<form>
<input v-model="anyNum" type="number" >
<button @click.prevent="submitForm()">
Submit
</button>
</form>
</template>
However, when I change the Javascript object data
to a function, then data.test
correctly captures the computed value of squared
. Visit this fiddle for reference.
<script setup>
import { ref, computed } from 'vue'
const anyNum = ref(2)
const square = computed(() => {
return anyNum.value * anyNum.value
})
const data = () => {
return {
test: square.value <===== captures the correct value
}
}
function submitForm() {
console.log(data())
}
</script>