【问题标题】:Vuex not reactiveVuex 没有反应
【发布时间】:2020-10-22 23:15:56
【问题描述】:

我尝试从在视图中直接使用我的 API 绑定转换为将所有逻辑放入 Vuex。我之前只是使用 Vuex 来存储实体,并将列表调用作为一个操作包含在内。在我看来,例如,我发出了myAPI.create(...) 调用,然后调度了list 操作。这很好用。

转换后,我的视图对商店更新没有反应:

store/modules/vehicles.js:

import vehiclesAPI from "@/api/vehicles";

const vehicles = {
  namespaced: true,

  state: {
    vehicles: []
  },

  mutations: {
    SET_VEHICLES(state, vehicles) {
      state.vehicles = vehicles;
    }
  },

  actions: {
    list({ commit }) {
      return new Promise((resolve, reject) => {
        vehiclesAPI
          .list()
          .then(response => {
            const vehicles = response.data;
            commit("SET_VEHICLES", vehicles);
            resolve(response);
          })
          .catch(e => {
            reject(e);
          });
      });
    },

    create({ commit }, vehicle) {
      return new Promise((resolve, reject) => {
        vehiclesAPI
          .create(vehicle)
          .then(response => {
            resolve(response);
          })
          .catch(e => {
            reject(e);
          });
      });
    }
  },

  getters: {
    vehicles: state => (state.vehicles ? state.vehicles : [])
  }
};

export default vehicles;

在我的视图中,我映射了我的动作和吸气剂。要创建我调用的车辆

this.create(this.vehicle);
this.list();

使用适用于 Chrome 的 Vue DevTools 我注意到,来自 list 操作的突变 SET_VEHICLES 不包含创建的车辆。但是,在发出重新加载后,它可以工作。

我做错了什么?

有趣的是,当在setTimeout 中调用this.list() 时,它会起作用。但是当我使用 create() 承诺 thenfinally 时它不起作用。

【问题讨论】:

    标签: vue.js vue-component vuex vuex-modules vue-reactivity


    【解决方案1】:

    是因为动作默认是异步的,你应该这样使用:

    this.create(this.vehicle)
        .then( () => this.list() )
    

    【讨论】:

    • 哇,谢谢伙计!我误用了.then() 并写了类似.then(this.list()) 的东西。再次感谢!
    • 是的,回调有时会令人困惑:)。太好了,解决了!
    猜你喜欢
    • 2020-10-28
    • 2019-04-24
    • 2021-02-21
    • 2022-06-21
    • 2021-06-01
    • 2020-11-28
    • 2021-09-20
    • 2021-10-20
    • 2020-10-06
    相关资源
    最近更新 更多