vue.js - Vuex 应用程序中“路由器”和“商店”之间的循环依赖关系
问题描述
我有一个带有路由器的 vue.js 应用程序,可以使用以下代码防止未经授权打开页面:
import Router from 'vue-router';
import store from '../store/index';
function guardAuth(to, from, next) {
if (store.state.authorizationToken) {
next();
} else {
next({
name: 'login',
query: { redirect: to.fullPath },
});
}
}
export default new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'toroot',
redirect: 'login',
},
{
path: '/overview',
component: Overview,
beforeEnter: guardAuth,
},
....
以及在 API 调用失败时调用的存储突变:
import axios from 'axios';
import Cookies from 'js-cookie';
import router from '../router/index';
export default new Vuex.Store({
state: {
mutations: {
handleApiFail(state, err) {
if (err && !axios.isCancel(err) && state.authorizationToken) {
// Block subsequent logout calls.
state.authorizationToken = null;
// Clear the token cookie just in case.
Cookies.set('authorizationToken', null);
// Stop the current and subsequent requests.
state.cancellationSource.cancel('Authorization token has expired.');
router.push({ name: 'login', query: { expired: '1', redirect: window.location.pathname } });
}
},
从上面的代码中可以看到“路由器”导入“商店”和“商店”导入“路由器”,据我所知,这会导致“商店”在“guardAuth()”中未定义。显然,我可以通过将“handleApiFail”移动到单独的“.js”文件来摆脱这种循环依赖,但我不确定这是一个好主意。是否有更好的解决方案或一些通用方法来解决这种情况?'handleApiFail' 应该是一个突变还是一个简单的函数?突变可以使用“路由器”吗?我真的需要摆脱循环依赖吗(例如,在 C++ 中我不需要)?
解决方案
与突变相比,在单独的函数中失败会更好。如果您想在进入路线之前检查它。你可以beforeEnter()
在你的路线上使用。
检查此文档或beforeEnter
其他路由属性
推荐阅读
- java - 如何解决第 27、43 行中表达式的非法开头?
- mongodb - mongoose 的“有独立工作收入的员工”模式设计的问题
- javascript - 尝试使用文本初始化编辑器时出现“n.createFromText 不是函数”错误
- python - 使用 SMTP 通过 python 发送邮件
- c# - EF Core 3.1 - 断开连接的图 - 导航属性 - 实体已跟踪异常 - 前进的方向
- python - 在一定范围内删除字典中的键/值对
- typescript - AWS CDK - 如果密钥管理器中缺少密钥,则引发错误
- servicestack - ServiceStack .NET 标准库缺少 PublicKeyToken
- awk - 使用 awk 打印由 / 分隔的字段
- php - Codeigniter 3 - 访问数组未按预期工作