vue3中給數(shù)組賦值丟失響應式的解決
vue3給數(shù)組賦值丟失響應式的解決
由于vue3使用proxy,對于對象和數(shù)組都不能直接整個賦值。
只有push或者根據(jù)索引遍歷賦值才可以保留reactive數(shù)組的響應性
const arr = reactive([]);
const load = () => {
const res = [2, 3, 4, 5]; //假設請求接口返回的數(shù)據(jù)
// 方法1 失敗,直接賦值丟失了響應性
// arr = res;
// 方法2 這樣也是失敗
// arr.concat(res);
// 方法3 可以,但是很麻煩
res.forEach(e => {
arr.push(e);
});
// 方法4 可以
// arr.length = 0 // 清空原數(shù)組
arr.push(...res)
}
或者
const state = reactive({
arr: []
});
...
state.arr = res
...
或者
const state = ref([]); ... state.value= res ...
例子
<template>
<div class="content">
...
<Card title="content組件">
<button @click.prevent="add">ADD</button>
<button @click.prevent="pop">POP</button>
<button @click.prevent="changeList">changeList</button>
{{ list }}
<ProInj></ProInj>
</Card>
</div>
</template>
<script setup lang="ts">
import { reactive, markRaw, ref, defineAsyncComponent, inject, Ref } from 'vue'
...
let flag = ref(true)
let list = inject<Ref<number[]>>('list',ref(reactive<number[]>([])))
// let list = inject<Ref<number[]>>('list', ref<number[]>([1, 2, 3]))
const add = () => list.push(list!.length + 1)
const pop = () => list.pop()
const changeList = () => {
flag.value = !flag.value
if (flag.value) {
list.length = 0
list.push(...[9, 5, 4, 1])
}
else {
list.length = 0
list.push(...[6, 6, 6, 6, 6])
}
}
...
</script>
<style lang="less" scoped>
...
</style>
效果圖:

reactive響應式數(shù)據(jù)賦值丟失響應式問題
reactive響應式數(shù)據(jù)賦值問題
const ?list = reactive({})當你接收到接口數(shù)據(jù),不要直接賦值 比如 list = data
這樣會丟失響應式!
你可以這樣做:
?? ?const ?list = reactive({
?? ?arr:[]
})
list.arr = data.arr或者
將list聲明為ref方式
const list = ref([]) list.value = data
這樣也不會丟失響應式
原因:reactive聲明的響應式對象被list代理 操作代理對象需要有代理對象的前綴,直接覆蓋會丟失響應式
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue3內(nèi)嵌iframe的傳參與接收參數(shù)代碼示例
這篇文章主要給大家介紹了關(guān)于vue3內(nèi)嵌iframe的傳參與接收參數(shù)的相關(guān)資料,Vue項目中使用iframe及傳值功能相信有不少人都遇到過,需要的朋友可以參考下2023-07-07
vue項目實現(xiàn)表單登錄頁保存賬號和密碼到cookie功能
這篇文章主要介紹了vue項目實現(xiàn)表單登錄頁保存賬號和密碼到cookie功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08
解決element?ui?cascader?動態(tài)加載回顯問題
這篇文章主要介紹了element?ui?cascader?動態(tài)加載回顯問題解決方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08
ElementUI中el-dropdown-item點擊事件無效問題
這篇文章主要介紹了ElementUI中el-dropdown-item點擊事件無效問題及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04

