Vuex商店不更新

时间:2019-08-01 02:36:35

标签: vue.js vuex

我一直在重构我的Vue SPA,我要进行的更改之一是删除了在需要它的每个组件中手动导入“ Store”,而改为使用“ this。$ store.dispatch(' module / update',data)”,但不会像过去那样更新商店“ Store.dispatch('module / update',data)”。

    methods: {
      update() {
        let office = {
          id: this.office.id,
          name: this.name,
          description: this.description,
          abbreviation: this.abbreviation
        };

        this.$http.post('/api/office/update', office).then(function(result) {
          Store.dispatch('offices/update', result.data);
          this.$router.push({ path: '/settings/offices' });
        }).catch((error) => {
          this.$router.push({ path: '/settings/offices' });
        });
      }
    }
export const Offices = {
  namespaced: true,
  state: {
    all: []
  },
  mutations: {
    ADD_OFFICE: (state, offices) => {
      offices.forEach(office => {
        state.all.push(office);
      });
    },
    DELETE_OFFICE: (state, id) => {
      state.all.splice(state.all.map((office) => { return office.id }).indexOf(id), 1);
    },
    UPDATE_OFFICE: (state, data) => {
      Object.assign(state.all.find((office) => office.id === data.id), data);
    }
  }, 
  actions: {
    get(context) {
      Axios.get('/api/office/all').then((response) => {
        context.commit('ADD_OFFICE', response.data);
      });
    },
    create(context, office) {
      context.commit('ADD_OFFICE', office);
    },
    update(context, data) {
      context.commit('UPDATE_OFFICE', data);
    },
    delete(context, id) {
      context.commit('DELETE_OFFICE', id);
    }
  }
}

我希望它可以像手动导入一样更新商店。

1 个答案:

答案 0 :(得分:0)

突变应该是不变的,以使数据具有反应性

 mutations: {
    ADD_OFFICE: (state, offices) => {
      state.all = state.all.concat(offices)
    },
    DELETE_OFFICE: (state, id) => {
      state.all = state.all.filter(office => office.id != id)
    },
    UPDATE_OFFICE: (state, data) => {
      const officeIndex = state.all.findIndex(office => office.id === data.id)
      const newObj = Object.assign(state.all[officeIndex], data)
      state.all = [
        ...state.all.slice(0, officeIndex),
        newObj,
        ...state.all.slice(officeIndex + 1)
      ]
    }
  },