SoFunction
Updated on 2025-04-05

Ref and reactive define array methods in vue3

vue3's ref and reactive definition array

In vue3, there are generally two ways to define responsive data:

  • ref 
  • reactive

Generally speaking, we use ref to define basic data types and reactive to define complex data types.

But you can also use ref to define an array

1. Ref defines an array

import { ref } from 'vue'
const arr = ref([])

Two situations:

  • Initialize the array when defined
  • The array was not initialized when defined

Initialize the array

import { ref,watch } from 'vue'
const arr = ref([1,2,3])
watch(, () => { //At this time, it can be monitored by directly modifying and using array methods  ('The array has changed')
})
const pushArray = () => {
  (0, 0, 19)
}
const changeArrayItem = () => {
  [0] = 10
}

Uninitialized array

import { ref,watch,onMounted } from 'vue'
const arr = ref([])
watch( //This time, .value cannot be used and must be deep monitoring. This writing method can not only listen to changes in the array itself, but also listen to changes in array elements.  arr,
  () => {
    ('Empty array has changed')
  },
  {
    deep: true
  }
)
const pushArray = () => {
  (0, 0, { value: 12 })
}
const changeArrayItem = () => {
  [0] = { value: 32 }
}
onMounted(() => {
   = [{ value: 5 }, { value: 2 }, { value: 3 }, { value: 4 }]
})

2. Reactive defines array

import { reactive } from 'vue';
let arr = reactive([])
function change(){
   let newArr = [1,2,3]
   arr = newArr
}

However, there will be problems if defined in this way. The step arr = newArr makes arr lose its responsive effect.

Solution

You can use ref to define, use push method, and nest an object outside the array

import { reactive,ref } from 'vue';
let arr = reactive([])
function change(){
   let newArr = [1,2,3]
   arr = newArr
}
// Method 1: Use reflet arr = ref([])
function change(){
   let newArr = [1,2,3]
    = newArr
}
// Method 2: Use push methodlet arr = reactive([])
function change(){
   let newArr = [1,2,3]
   (...newArr)
}
// Method 3: Nesting an object in the outer layerlet arr = reactive({list:[]})
function change(){
   let newArr = [1,2,3]
    = newArr
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.