Here's the code. No errors or anything, but the output doesn't update as expected.
<script setup >
import { ref, reactive } from 'vue'
const arr = reactive([2,4,6])
setTimeout(()=> { arr.value = [1, 3, 5, 7] }, 500) // This doesn't work!
</script>
<template>
<h2 v-for="v in arr"> val {{ v }}</h2>
</template>
CodePudding user response:
If you are using reactive
, you get back an object where you can set its properties without value
. You either define an object where arr
is a property:
const state = reactive({
arr: [2, 4, 6]
})
setTimeout(()=> {state.arr = [1,3,5,7]}, 500)
Or for arrays I'd suggest using ref
instead, then the rest of your code should work:
const arr = ref([2, 4, 6])
CodePudding user response:
setTimeout
can be pretty tricky regarding its context, and reactive
also have its quirks.
Hence I do recommend using the following
<script setup>
import { useTimeoutFn } from "@vueuse/core"
import { ref } from "vue"
let arr = ref([2, 4, 6])
const { start } = useTimeoutFn(() => {
arr.value = [1, 3, 5, 7]
}, 500)
start()
</script>
<template>
<h2 v-for="v in arr" :key="v">val {{ v }}</h2>
</template>
useTimeoutFn
is an official helper "hook" maintained by the Vue team.
The VueUse project is plenty of super useful functions like that, give it a try!