In vue3, there are generally two ways to define responsive data: ref and 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 arrays
1. Ref defines an array
import { ref } from 'vue'
const arr = ref([])
Two cases: the array is initialized when it is defined, and the array is not initialized when it is defined
Initialize the array
import { ref,watch } from 'vue'
const arr = ref([1,2,3])
watch(arr.value, () => { //这个时候通过直接修改和利用数组的方法修改都可以监测到
console.log('数组变化了')
})
const pushArray = () => {
emptyArray.value.splice(0, 0, 19)
}
const changeArrayItem = () => {
emptyArray.value[0] = 10
}
uninitialized array
import { ref,watch,onMounted } from 'vue'
const arr = ref([])
watch( //这个时候不能用.value且必须是深度监听,这种写法不仅可以监听数组本身的变化,也可以监听 数组元素的变化
arr,
() => {
console.log('空数组变化了')
},
{
deep: true
}
)
const pushArray = () => {
arr.value.splice(0, 0, { value: 12 })
}
const changeArrayItem = () => {
arr.value[0] = { value: 32 }
}
onMounted(() => {
arr.value = [{ value: 5 }, { value: 2 }, { value: 3 }, { value: 4 }]
})
2. Reactive defines an array
import { reactive } from 'vue';
let arr = reactive([])
function change(){
let newArr = [1,2,3]
arr = newArr
}
But there will be problems with this definition, arr = newArr This step makes arr lose the responsive effect
Solution: You can use ref definition, 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
}
// 方法一:使用 ref
let arr = ref([])
function change(){
let newArr = [1,2,3]
arr.value = newArr
}
// 方法二:使用push 方法
let arr = reactive([])
function change(){
let newArr = [1,2,3]
arr.push(...newArr)
}
// 方法三:外层嵌套一个对象
let arr = reactive({list:[]})
function change(){
let newArr = [1,2,3]
arr.list = newArr
}