vue.jsvuejs3vue-composition-apivue-sfc

Can't update entire reactive array with vuejs


Here's the code. No errors or anything, but the output doesn't update as expected.

Code in Vue SFC Playground

<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>

Solution

  • 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])