我正在构建一个使用 Vue Router 和 Pinia 进行状态管理的 Vue 3 应用程序。
在我的全局状态下,我定义了一个属性,它告诉我用户是否已登录,以便用户可以在应用程序中导航。但是,登录过程由 Cognito 处理,所以一旦我进入应用程序,我点击登录按钮,它会将我带到一个处理登录过程的 Cognito 屏幕,然后将我重定向回我的应用程序的主页。
因此,在重定向之后,我从生成的 URL 中提取了一些参数,并且我想将它们保存在全局状态中,为此我使用beforeEach
防护来解析 URL,检查参数,更新存储,然后从中读取以检查有效的会话。
但我的问题是导航甚至在状态更新之前仍在继续。我最终使用setTimeout
只是为了看看等待是否解决了这个问题,它确实
router.beforeEach((to) => {
const mainStore = useMainStore();
if (to.name === 'Login') {
return;
}
if (to.hash !== '') {
const queryParams = window.location.href.split('&');
const paramValues = queryParams.map(param => {
})
const payload = {
id_token: paramValues.find(param => param.name === 'id_token').value,
access_token: paramValues.find(param => param.name === 'access_token').value,
token_type: paramValues.find(param => param.name === 'token_type').value,
isAuthenticated: true
}
//Here I'm trying to update my global state
mainStore.updateTokens(payload);
}
// Here I use timeout, but before I just had the check for the property
setTimeout(() => {
if (!mainStore.isAuthenticated) return '/login';
}, 3000)
});
我应该如何处理这种情况?我读过关于beforeResolve
守卫的文章,但我不确定如何使用它;基本上我只需要知道在导航期间我应该如何执行一些异步操作(比如从服务器获取数据),而不是在组件内部。