javascript - VueJS - Vuex 突变和 Vue-Router 重定向的正确顺序?
问题描述
我试图弄清楚 Vuex 突变和 VueRouter 重定向的顺序在我的用例中是否重要。
我有两个动作;logout
和whoami
:
- 我们在路上
/app
。它通过 a 保护middleware
,只有在登录时才能访问,并且它state.user
使用template
. - 用户触发
logout
action
. logout
邮寄whoami
到/logout
.whoami
提交用户的信息(到null
)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 的“反应式”代码触发太慢了吗?我可以依赖这种行为吗?
解决方案
推荐阅读
- javascript - 如何在移动应用程序中隐藏颤动的 webview
- firebase - Future Builder 不显示来自 Cloud Firestore 的数据
- java - 如何从java调用Nodejs函数
- python-3.x - 有什么方法可以跟踪 shutil.make_archive() 的进度吗?
- javascript - 组件正在将文本类型的受控输入更改为不受控制。输入元素不应从受控切换到不受控
- pointers - 在没有通道的情况下同时计算斐波那契,但指针不起作用
- distributed - 为什么当消费者在 MassTransit RouterSlip 中抛出异常时不调用 Compensate 方法
- jquery - 我如何通过定价 00 美元的产品来查询 WooCommerce 产品?
- javascript - 如何通过 JavaScript 避免图像 src 字符串重复
- sql - 如何 PIVOT 查询中提到的选择结果