本文介绍了仅在VueJS中完成分派和提交后才触发路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确实有一个提交表单,该表单包含电子邮件和密码,然后将它们传递到名为 userSignIn

I do have a form submit which takes email and password then pass them into an action in store called userSignIn

SignIn.vue:

onSubmit () {
    if (this.$refs.form.validate()) {
    const user = {
        email: this.email,
        password: this.password
    }
    this.$store.dispatch('userSignIn', user)
        .then(() => {
            this.$router.push('/')
        }).catch(err => {
            console.log(err)
        })
    }
}

在商店内,我确实有一个 userSignIn 动作

Within store, I do have a userSignIn action like this

store.js操作:

userSignIn ({commit, getters}, payload) {
    getters.Api.post(`user/signin`, {
        email: payload.email,
        password: payload.password
    }).then(res => {
        commit('userSignIn', res.data.token)
    }).catch(err => {
        console.log(err)
    })
}

路由( this。$ router.push('/'))仅在 userSignIn commit( commit('userSignIn',res.data.token))。但是实际发生的路由触发是在提交之前触发的,由于未设置用户令牌,因此会导致错误。

The routing(this.$router.push('/')) should only be done after userSignIn commit(commit('userSignIn', res.data.token)). But what actually happening routing triggers before commit, which results and error because user token is not set yet.

如何触发某些操作(在这种情况下, this。$ router.push('/'))仅在 dispatch commit 之后完成

How to trigger something(in this case this.$router.push('/')) only after completion of dispatch and commit within it?

推荐答案

兑现承诺就成功了。

userSignIn ({commit, getters}, payload) {
    return getters.Api.post(`user/signin`, {
        ......
    })

这篇关于仅在VueJS中完成分派和提交后才触发路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 07:51