Triggering a route only after dispatch and commit completed in VueJS

六眼飞鱼酱① 提交于 2019-12-24 13:33:37

问题


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)
        })
    }
}

Within store, I do have a userSignIn action like this

store.js actions:

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)
    })
}

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.

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


回答1:


Returning the promise did the trick.

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


来源:https://stackoverflow.com/questions/49113023/triggering-a-route-only-after-dispatch-and-commit-completed-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!