调用vuex操作时如何传递对组件的引用

时间:2018-01-29 19:44:01

标签: vue.js vuex

我对vue很新(对vuex来说很新)。我想将一些axios api调用移动到我的Vuex商店中。我知道有例如:

  actions:{
    LOAD_USER: function ({ commit }) {
      axios.get('/arc/api/v1/me', {dataType: 'json'})
      .then((response )=> {
        commit('SET_USER', { user: response.data.user })
      })
      .catch(function (error) {
        console.log(error.message);
      });

并通过以下方式在我的调用组件中调用它:

  this.$store.dispatch('LOAD_USER')

这是有效的。我的问题是我需要将调用组件中的一些变量设置为false或者杀死进度条。这是我以前在我的调用组件中使用的内容:

  this.loading = true
  this.$Progress.start()
  axios.get('/arc/api/v1/me', {dataType: 'json'})
  .then((response )=> {
    this.$Progress.finish()
    this.loading = false
    this.$store.state.user = response.data.user;
    this.user = this.$store.state.user
  })
  .catch(function (error) {
    this.$Progress.fail()
    console.log(error.message);
  });

如何将这些加载行为整合到我的vuex操作中?如何通过此调用传递对组件的引用:

  this.$store.dispatch('LOAD_USER')

还是有更好的解决方案?

2 个答案:

答案 0 :(得分:2)

操作可以返回承诺https://vuex.vuejs.org/en/actions.html 我想你想要做的就是在你打电话给你的行动时激活加载,并在解决或拒绝承诺时停止加载。

// Action which returns a promise.
actions: {
  LOAD_USER ({ commit }) {
    return new Promise((resolve, reject) => {
      axios.get('/arc/api/v1/me', {dataType: 'json'})
        .then((response )=> {
          commit('SET_USER', { user: response.data.user })
          resolve()
        })
        .catch(function (error) {
          console.log(error.message);
          reject(error);
        });
    })
  }
}

// Update loading when the action is resolved.
this.loading = true;
store.dispatch('LOAD_USER').then(() => {
  this.loading = false;
})
.catch(function(error) {
  // When the promise is rejected
  console.log(error);
  this.loading = false;
});

如果使用上述方法无法实现目标,可以将加载布尔值添加到vuex商店并将其导入组件中。然后修改你的动作中的加载布尔值(使用突变)让视图更新。

注意:我不会传递对您的操作的引用。虽然这是可能的,但可能有更好的解决方案来解决您的问题。尝试尽可能保持组件中的视图逻辑。

答案 1 :(得分:1)

好吧,您始终可以使用Store.dispatch()的第二个参数将任何有效负载传递到相应的操作中:

this.$store.dispatch('LOAD_USER', this); // passing reference as payload

...但我强烈建议不要这样做。相反,我宁愿拥有VueX处理的整个状态(包括'loading'标志等)。

在这种情况下,基于异步API请求的单个action - LOAD_USER 会将两个mutations提交到Store:第一个设置loading在请求开始时标记,第二个将其重置为false - 并加载用户数据。例如:

LOAD_USER: function ({ commit }) {
  commit('LOADING_STARTED'); // sets loading to true
  axios.get('/arc/api/v1/me', {dataType: 'json'})
  .then(response => {
    commit('LOADING_COMPLETE'); // resets loading flag
    commit('SET_USER', { user: response.data.user });
  })
  .catch(error => {
    commit('LOADING_ERROR', { error }); // resets loading
    console.log(error.message);
  });

除了其他优点之外,当您的请求逻辑变得更复杂时,这种方法可以简化事情 - 包括错误处理,重试等。