Vue Router - 相同的路径,不同的组件
在 Vue Router 中,我想基于变量在同一路径中显示不同的组件。
如果 isFirstTimeAccess 为 true,我想显示欢迎组件,如果为 false,我想在浏览器上的同一路径中显示 AuthHandler 组件 -> /my-sub-url/
示例:
export const router = createRouter({
history: createWebHistory(),
routes: [{
path: '/my-sub-url/',
component: welcome,
beforeEnter(to, from, next) {
if (store.getters.isFirstTimeAccess) {
next();
} else {
next({
name: 'auth'
});
}
},
children: [{
name: 'auth',
path: '',
component: AuthHandler,
},
]
}
];
});
但是如果我尝试此代码,如果我设置:
isFirstTimeAccess === true ->它可以工作并显示欢迎组件
isFirstTimeAccess === false ->它在浏览器中向我显示此错误:
[Vue Router warn]:从“/”转到“/my-sub-url/”时在导航防护中检测到无限重定向。中止以避免堆栈溢出。如果不修复,这将导致生产中断。 vue-router.esm-bundler.js:72
[Vue Router warn]: 启动路由器时出现意外错误:错误:导航防护中无限重定向
有人可以帮助我吗?
In Vue Router I want to show different components in the same path, based on a variable.
If isFirstTimeAccess is true i want to show Welcome Component, if it is false I want to show AuthHandler component in the same path on the browser -> /my-sub-url/
Example:
export const router = createRouter({
history: createWebHistory(),
routes: [{
path: '/my-sub-url/',
component: welcome,
beforeEnter(to, from, next) {
if (store.getters.isFirstTimeAccess) {
next();
} else {
next({
name: 'auth'
});
}
},
children: [{
name: 'auth',
path: '',
component: AuthHandler,
},
]
}
];
});
but If i tried this code if I set :
isFirstTimeAccess === true -> it works and show the welcome component
isFirstTimeAccess === false -> it show me this error in browser:
[Vue Router warn]: Detected an infinite redirection in a navigation guard when going from "/" to "/my-sub-url/". Aborting to avoid a Stack Overflow. This will break in production if not fixed.
vue-router.esm-bundler.js:72
[Vue Router warn]: Unexpected error when starting the router: Error: Infinite redirect in navigation guard
Can someone help me please?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个方法
Try this way
这似乎是 Vue Router 的 导航守卫 的完美案例。他们甚至还有像您这样的身份验证案例的具体示例。
刚刚从那里复制:
This seems to be a perfect case for Vue Router's navigation guards. They even have a specific example for an authentication case like yours.
Just copied from there: