【问题标题】:Triggering a route only after dispatch and commit completed in VueJS仅在 VueJS 中完成调度和提交后触发路由
【发布时间】:2018-03-05 14:46:10
【问题描述】:

我确实有一个表单提交,它接受电子邮件和密码,然后将它们传递到名为 userSignIn 的商店中的操作中

登录.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('/'))?

【问题讨论】:

    标签: vue.js vuejs2 es6-promise vue-router vuex


    【解决方案1】:

    返回承诺就可以了。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-05
      • 1970-01-01
      相关资源
      最近更新 更多