vue.js - Vuex 突变未更新状态
问题描述
我这里有点问题。在我刷新页面之前,我的突变不会更新状态。
行动
async restoreDeletedCours({ commit }, cours) {
let response = await Axios.post("/dashboard/school/cours/restoreDeletedCours", cours);
let crs = response.data.data;
if (response.status == 200 || response.status == 201) {
commit("REMOVE_COURS_FROM_DELETED_LIST", crs);
commit("RESTORE_SCHOOL_DELETED_COURS", crs);
return response.data;
}
}
突变
REMOVE_COURS_FROM_DELETED_LIST(state, crs) {
// Let's remove the restored Item from deleted List
let removeFromDeletedList = state.deletedCourses.filter(c => c.id != crs.id);
state.deletedCourses = removeFromDeletedList;
}
解决方案
问题是Mutation 的反应性,你改变数组的方式不是反应性的,如果处理得当,数组是反应性的,无论它们是来自组件的局部变量还是 Vuex 状态它们具有相同的行为:
此分配对数组没有反应
state.deletedCourses = removeFromDeletedList;
试试这个:
突变:
REMOVE_COURS_FROM_DELETED_LIST(state, crs) {
//We get the indexes that we have to remove
let indexArr = state.reduce(function(acc, val, index) {
if (val != crs.id) {
acc.push(index);
}
return acc;
}, []);
//We iterate this indexes and mutate properly the state array so changes are reactive
indexArr.forEach( i => state.deletedCourses.splice(i,1) );
}
推荐阅读
- objective-c - 在objectiveC中定义半公共变量
- python - 有没有一种很好的pythonic方法来进行左值排列?
- python - 只有用户名和密码(没有我们的证书和私钥)
- laravel - Laravel 5.8 的 auth.reminder.repository
- java - 带有gridView的ListView的可点击元素(Android)
- javascript - 如何使用 inlineCode 在无服务器中定义 lambda 函数?
- windows - 运行时相同的二进制但不同的汇编指令 - Windows 7
- arduino - Ardino-Nano-BLE-Sense“用声音发送数据”啁啾项目问题
- python - 当我将 pandas 的箱线图与子图一起使用时出现错误
- php - 根据所选项目过滤 Json