vue3使用reactive包裹數(shù)組正確賦值問題
使用reactive包裹數(shù)組正確賦值
需求:將接口請求到的列表數(shù)據(jù)賦值給響應(yīng)數(shù)據(jù)arr
const arr = reactive([]); const load = () => { const res = [2, 3, 4, 5]; //假設(shè)請求接口返回的數(shù)據(jù) // 方法1 失敗,直接賦值丟失了響應(yīng)性 // arr = res; // 方法2 這樣也是失敗 // arr.concat(res); // 方法3 可以,但是很麻煩 res.forEach(e => { arr.push(e); }); };
vue3使用proxy
,對于對象和數(shù)組都不能直接整個賦值。
使用方法1能理解,直接賦值給用reactive
包裹的對象也不能這么做。
方法2為什么不行?
只有push或者根據(jù)索引遍歷賦值才可以保留reactive數(shù)組的響應(yīng)性?
如何方便的將整個數(shù)組拼接到響應(yīng)式數(shù)據(jù)上?
提供幾種辦法
const state = reactive({ arr: [] }); state.arr = [1, 2, 3]
或者
const state = ref([]) state.value = [1, 2, 3]
或者
const arr = reactive([]) arr.push(...[1, 2, 3])
這幾種辦法都可以觸發(fā)響應(yīng)性,推薦第一種
vue3的reactive重新賦值無效
vue3官方的文檔說明
reactive() 返回一個對象的響應(yīng)式代理
所以 reactive 方法應(yīng)該作用于一個對象Object,如果要使用數(shù)組,則需要包裝一下:
let list = reactive({ ?? ?data: [{id: 01, name: 'XXX'}] })
或者使用 ref:
let list = ref([{id: 1, name: 'Andy'}])
已下引用原作者的代碼:
import { reactive, ref } from 'vue' export default { ? setup() { ? ? // 需要一個帶默認(rèn)值的數(shù)組list; ? ?? ?let list = reactive([{id: 1, name: 'Andy'}]) ? ?? ? ? // 每次觸發(fā)事件重置list,把新值放入,此種方式不會觸發(fā)視圖更新 ? ? const checkBtn = () => { ? ? ? // 此時重置操作 地址指向變成一個新的地址,不會觸發(fā)視圖更新 ? ? ? list = [{id: 1, name: 'Andy'}] ? ? ? list.push({id: 2, name: 'Lucy'}) ? ? } ? ?? ? ? // -------------------------------------------------- ? ? // 正確的重置處理方法如下:使用reactive將數(shù)組包裹到一個對象中 ? ? let list = reactive({ ? ? ? data: [{id: 1, name: 'Andy'}] ? ? }); ? ? const checkBtn = () => { ? ? ? list.data = [{id: 1, name: 'Andy'}] ? ? ? list.data.push({id: 2, name: 'Lucy'}) ? ? } ? ? // 或者使用ref ? ? let list = ref([{id: 1, name: 'Andy'}]); ? ? const checkBtn = () => { ? ? ? list.value = [{id: 1, name: 'Andy'}] ? ? ? list.value.push({id: 2, name: 'Lucy'}) ? ? } ? ? return { ? ? ? list, ? ? ? checkBtn ? ? } ? }, }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue@cli3項目模板怎么使用public目錄下的靜態(tài)文件
這篇文章主要介紹了vue@cli3項目模板怎么使用public目錄下的靜態(tài)文件,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07Vue子組件如何修改父組件數(shù)據(jù)的方法及注意事項
這篇文章主要介紹了Vue子組件如何修改父組件數(shù)據(jù)的方法及注意事項,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06