首页 > 解决方案 > 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;
}

在此处输入图像描述

标签: vue.jsvuejs2vuexvuex-modules

解决方案


问题是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) );

}

推荐阅读