Vue3 重置覆盖 reactive 数组数据的方法
核心要点:
- 通过splice删除原数组内的所有数据,并添加新的数据进去。
- 潜在影响:大数据量下,splice重置数组和 ref 的.value重新赋值重置数组,哪个耗时短还需自行测试。
通过 `splice` 传入0 和 Infinity 来删除原数组从头到尾的内容,然后`...[]`将新数据丢进响应式数组里。
<template><button @click="c2()">测试按钮</button>
</template><script setup lang="ts">
import { reactive, watch } from 'vue'
const arr1 = reactive([1,2,3,4])
watch(arr1,(val)=>{console.log(...val);
})
function c2() {arr1.push(arr1.length+1)
}setTimeout(() => {arr1.splice(0,Infinity,...[11,22,33,44])
}, 6000);</script>