vue3中給數(shù)組賦值丟失響應(yīng)式的解決
vue3給數(shù)組賦值丟失響應(yīng)式的解決
由于vue3使用proxy,對(duì)于對(duì)象和數(shù)組都不能直接整個(gè)賦值。
只有push或者根據(jù)索引遍歷賦值才可以保留reactive數(shù)組的響應(yīng)性
const arr = reactive([]);
const load = () => {
const res = [2, 3, 4, 5]; //假設(shè)請(qǐng)求接口返回的數(shù)據(jù)
// 方法1 失敗,直接賦值丟失了響應(yīng)性
// 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響應(yīng)式數(shù)據(jù)賦值丟失響應(yīng)式問(wèn)題
reactive響應(yīng)式數(shù)據(jù)賦值問(wèn)題
const ?list = reactive({})當(dāng)你接收到接口數(shù)據(jù),不要直接賦值 比如 list = data
這樣會(huì)丟失響應(yīng)式!
你可以這樣做:
?? ?const ?list = reactive({
?? ?arr:[]
})
list.arr = data.arr或者
將list聲明為ref方式
const list = ref([]) list.value = data
這樣也不會(huì)丟失響應(yīng)式
原因:reactive聲明的響應(yīng)式對(duì)象被list代理 操作代理對(duì)象需要有代理對(duì)象的前綴,直接覆蓋會(huì)丟失響應(yīng)式
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vuecli3打包后出現(xiàn)跨域問(wèn)題,前端配置攔截器無(wú)效的解決
這篇文章主要介紹了vuecli3打包后出現(xiàn)跨域問(wèn)題,前端配置攔截器無(wú)效的解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
vue簡(jiǎn)單實(shí)現(xiàn)轉(zhuǎn)盤抽獎(jiǎng)
這篇文章主要為大家詳細(xì)介紹了vue簡(jiǎn)單實(shí)現(xiàn)轉(zhuǎn)盤抽獎(jiǎng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-03-03
Vue之Vue.set動(dòng)態(tài)新增對(duì)象屬性方法
下面小編就為大家分享一篇Vue之Vue.set動(dòng)態(tài)新增對(duì)象屬性方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-02-02
vue使用vant中的checkbox實(shí)現(xiàn)全選功能
這篇文章主要為大家詳細(xì)介紹了vue使用vant中的checkbox實(shí)現(xiàn)全選功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-11-11

