首页 文章

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

提问于
浏览
0

我对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 回答

  • 1

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

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

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

    在这种情况下,基于异步API请求的单个action - LOAD_USER 将提交两个mutations来存储:第一个在请求启动时设置 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);
      });
    

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

  • 1

    操作可以返回一个承诺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存储区并将其导入组件中 . 然后修改你的动作中的加载布尔值(使用突变)让视图更新 .

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

相关问题