I have a function that produces variables. I need them to be reactive - it might change in time, however Vue does not track these changes
<template>
{{ parse('foo') }}
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
function parse(param) {
const target = ref('initial value')
setTimeout(() => {
target.value = 'changed value'
}, 3000)
return target
}
return { parse }
},
}
</script>
CodePudding user response:
It's not a good practice to call a method inside template in order to render something, you could define the reactive data outside the function and run the function in the setup or the onMounted
hook to modify the target property :
<template>
{{ target }}
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const target = ref('initial value')
function parse(param) {
setTimeout(() => {
target.value = 'changed value'
}, 3000)
}
//call the function
parse('foo')
return { target }
},
}
</script>
CodePudding user response:
I think you are expecting initial value to be displayed and after 3 seconds it being changed to changed value however, in your code you are defining target inside the function so initial value is never being returned but instead only changed value is.
instead const target = ref('initial value')
should be defined outside of your function and then the function should be called accordingly
<template>
{{ target }}
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const target = ref('initial value')
function parse(param) {
setTimeout(() => {
target.value = 'changed value'
}, 3000)
}
parse('foo')
return { target }
},
}
</script>