I have a parent component that has a ref variable that is set after a fetch request, and I'm trying to pass it to a child card component that has a little animation that counts up to that number, but I think I'm not passing it correctly.
The variable shows up correctly and is reactive when referenced directly on the page in the parent and in the child, but when referenced in a data variable it only receives the first value.
in parent component:
<script setup>
// etc...
var myNumber = ref(0)
const fetchMyNumber = async () => {
// fetch function etc
// on success:
myNumber.value = Number(fetchedNumber)
}
// etc...
</script>
<template>
<div>
{{ myNumber }} // displays the correct fetchedNumber
<count-up :to="myNumber" /> // only ever shows 0
</div>
</template>
in my count-up card component:
<script>
import { nth } from '@/utils/charts'
export default {
name: 'CountUp',
props: {
currency: {
type: Boolean,
default: false
},
suffix: {
type: Boolean,
default: false
},
percent: {
type: Boolean,
default: false
},
to: {
type: Number,
default: null
}
},
data() {
return {
count: 0,
interval: null,
end: this.to // returns 0
}
},
computed: {
// end() {
// return this.to // also returns 0
// },
increment() {
console.log('end: ' + this.end) // sees 0
return Math.ceil(this.end / 30)
}
},
mounted() {
this.interval = setInterval(this.tick, 20)
},
methods: {
tick() {
if (this.count + this.increment >= this.end) {
this.count = this.to.toLocaleString()
return clearInterval(this.interval)
}
this.count += this.increment
}
}
}
</script>
<template>
<div>
{{ to }} // returns correct number!!!
<span v-text="count" /> // Returns 0!
</div>
</template>
I checked typeof() in both parent and child and both are Number, which is what the child asks for
I tried using a computed function instead of a data variable inside of the child, but it also returns 0
When I pass a number that isn't pulled from fetch, it works correctly, for example:
<count-up :to="1234" /> //works correctly
I tried switching to parseInt or parseFloat instead of Number and that didn't work
I get no errors in console
And then occasionally, when I save something in my IDE and my project hot-updates, it works! Which makes me think I'm just not passing the ref correctly. What am I doing wrong?