首页 > 解决方案 > VueJS - Vuex 突变和 Vue-Router 重定向的正确顺序?

问题描述

我试图弄清楚 Vuex 突变和 VueRouter 重定向的顺序在我的用例中是否重要。

我有两个动作;logoutwhoami

  1. 我们在路上/app。它通过 a 保护middleware,只有在登录时才能访问,并且它state.user使用template.
  2. 用户触发logout action.
  3. logout邮寄whoami/logout.
  4. whoami提交用户的信息(到null
  5. login重定向到/.

方法:

logout({ dispatch }) {
    Axios.post('logout').then(response => {
        dispatch('whoami').then(() => {
            router.replace('/').catch(err => {})
        })
    }).catch(error => {
        dispatch('whoami').then(() => {
            router.replace('/').catch(err => {})
        })
    })
},

因为用户的数据会很快“消失”(变成null),所以 VueApp 会出错,因为用户的数据正在显示在/app路由中(user.name现在是未定义的,因为user现在是null因为mutation)。然后应用程序重定向到/所有使用的user目标if-statements,检查用户是否登录。

所以作为一个修复我想,为什么不将重定向移动到whoami方法(可选):

whoami({ commit }, redirect=null) {
    return new Promise((resolve, reject) => {
        Axios.post('whoami').then(response => {
            if (response.data.id !== null) {
                commit('login', response.data)
            } else {
                commit('logout')
            }

            if (redirect !== null) {
                console.log(redirect.replace === true);
                if (redirect.replace === true) {
                    router.replace(redirect.to)
                } else {
                    router.push(redirect.to).catch(err => {})
                }
            }

            resolve(response)
        }).catch(error => {
            reject(error)
        })
    })
},

但这是奇怪的部分。在我的新方法中,whoami重定向出现commit. 然而没有出现类似的错误。

为什么是这样?这是因为 vue 的“反应式”代码触发太慢了吗?我可以依赖这种行为吗?

标签: javascriptvue.jspromisevuexvue-router

解决方案


推荐阅读