简体   繁体   English

Vuex 突变未更新状态

[英]Vuex Mutation not Updating State

I'm having a little of issue here.我这里有点问题。 My mutation doesn't update the state until I refresh the page.在我刷新页面之前,我的突变不会更新状态。

Action行动

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;
  }
}

MUTATION突变

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;
}

在此处输入图像描述

The problem is the reactivity of the Mutation , the way you are mutating the array is not reactive, arrays are reactive when treated well, whether they are local variables from a component or Vuex states they have the same behavior:问题是Mutation 的反应性,你改变数组的方式不是反应性的,如果处理得当,数组是反应性的,无论它们是来自组件的局部变量还是 Vuex 状态它们具有相同的行为:

This assignation is not reactive for arrays此分配对数组没有反应

state.deletedCourses = removeFromDeletedList;

Try this instead:试试这个:

Mutation:突变:

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) );

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM