【问题标题】:How can I handle a vuex dispatch response?如何处理 vuex 调度响应?
【发布时间】:2020-01-26 03:25:10
【问题描述】:

尽管我觉得答案可能就在我面前,但我还是举起白旗征求意见。

我有一个登录表单,我将其提交到 api (AWS) 并根据结果进行操作。我遇到的问题是,一旦调用了handleSubmit 方法,我就会立即进入console.log 语句......毫不奇怪,它会返回dispatch result: undefined

我意识到这可能不是 vue.js 的直接功能,而是我如何执行 javascript 集。

这是我的登录组件:

// SignInForm.vue

handleSubmit() {
    try {
        const {username, password} = this.form;

        this.$store.dispatch('user/authenticate', this.form).then(res => {
            console.log('dispatch result: ', res);
        });
    } catch (error) {
        console.log("Error: SignInForm.handleSubmit", error);
    }
},
...

这就是我的商店正在做的事情。我将它发送到我创建的UserService。一切都很好。我得到了正确的响应,并且可以记录我需要的所有内容。 UserService 正在发出 axios 请求 (AWS Amplify) 并返回响应。

// user.js (vuex store)

authenticate({state, commit, dispatch}, credentials) {
    dispatch('toggleLoadingStatus', true);

    UserService.authenticate(credentials)
        .then(response => {
            dispatch('toggleLoadingStatus', false);

            if (response.code) {
                dispatch("setAuthErrors", response.message);
                dispatch('toggleAuthenticated', false);
                dispatch('setUser', undefined);

                // send error message back to login component
            } else {
                dispatch('toggleAuthenticated', true);
                dispatch('setUser', response);

                AmplifyEventBus.$emit("authState", "authenticated");

                // Need to move this back to the component somehow
                //     this.$router.push({
                //         name: 'dashboard',
                //     });
            }

            return response;
        });
},
...

我遇到的问题是,如果我有错误,我可以在状态中设置错误,但我不确定如何在其他组件中访问它们。我尝试将data 属性设置为查看商店的计算方法,但出现错误。

如果我成功通过身份验证,我也在努力使用 vue-router。从我读过的内容来看,我真的不想在这个状态下这样做——这意味着我需要将成功响应返回给SignInForm 组件,这样我就可以使用 vue-router 来重定向用户到仪表板。

【问题讨论】:

    标签: javascript vue.js vuex aws-amplify


    【解决方案1】:

    是的。我只花了大约 6 个小时,发布到 SO,然后(再次)重新评估所有内容以找出答案。事实上,这是一个愚蠢的错误。但是为了帮助其他人,这就是我做错了什么......

    // SignInForm.vue
    
    async handleSubmit() {
        try {
            await this.$store.dispatch("user/authenticate", this.form)
                .then(response => {
                    console.log('SignInForm.handleSubmit response: ', response);  // works
    
                if (response.code) {
                    this.errors.auth.username = this.$store.getters['user/errors'];
                } else {
                    this.$router.push({
                        name: 'dashboard',
                    });
                }
            }).catch(error => {
                console.log('big problems: ', error);
            });
        } catch (error) {
            console.log("Error: SignInForm.handleSubmit", error);
        }
    },
    ...
    

    这是我的第一个错误:我从 async 方法调用另一个方法 - 但没有告诉该方法是 async,所以 call(er) 方法响应立即执行。这是更新后的 vuex 商店:

     // user.js (vuex store)
    
     async authenticate({state, commit, dispatch}, credentials) { // now async
        dispatch('toggleLoadingStatus', true);
    
        return await UserService.authenticate(credentials)
            .then(response => {
                console.log('UserService.authenticate response: ', response);  // CognitoUser or code
    
                dispatch('toggleLoadingStatus', false);
    
                if (response.code) {
                    dispatch("setAuthErrors", response.message);
                    dispatch('toggleAuthenticated', false);
                    dispatch('setUser', undefined);
                } else {
                    dispatch('toggleAuthenticated', true);
                    dispatch('setUser', response);
    
                    AmplifyEventBus.$emit("authState", "authenticated");
                }
    
                return response;
            });
    },
    ...
    

    我的第二个错误是我根本没有从 vuex 存储返回方法的结果。

    老办法:

    UserService.authenticate(credentials)
    

    更好的方法:

    return await UserService.authenticate(credentials)
    

    希望这可以为某人节省几个小时。 ¯_(ツ)_/¯

    【讨论】:

      【解决方案2】:

      这适用于 Vue3:

      export default {
          name: 'Login',
          methods: {
              loginUser: function () {
                  authenticationStore.dispatch("loginUser", {
                      email: 'peter@example.com',
                  })
                  .then(response => {
                      if (response.status === 200) {
                          console.log('Do something')
                      }
                  });
              },
          },
      }
      

      在商店中,您可以简单地传回作为承诺的 http 响应。

      const authenticationStore = createStore({
          actions: {
              loginUser({commit}, {email}) {
                  const data = {
                      email: email
                  };
      
                  return axios.post(`/authentication/login/`, data)
                      .then(response => {
                          toastr.success('Success')
                          return response
                      })
              },
      
          }
      })
      

      【讨论】:

        猜你喜欢
        • 2021-05-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-24
        • 2017-08-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多