仅在 VueJS 中完成分派和提交后才触发路由

Triggering a route only after dispatch and commit completed in VueJS

我确实有一个表单提交,它接受电子邮件和密码,然后将它们传递到商店中名为 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动作

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('userSignIn', res.data.token))之后完成。但是实际发生的路由在提交之前触发,这会导致错误,因为用户令牌尚未设置。

如何仅在dispatchcommit完成后触发某些东西(在本例中为this.$router.push('/'))?

返回 promise 就成功了。

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