gpt4 book ai didi

javascript - vue-router 的默认子路由

转载 作者:数据小太阳 更新时间:2023-10-29 05:06:58 26 4
gpt4 key购买 nike

我有一个 Vue 2.x 应用程序,我正在使用 vue-router 来处理路由。

在某些情况下,我必须直接显示一个子 vue。我的模板如下:

| voice 1 | voice 2 | voice 3 |

| submenu 1 | submenu 2 | submenu 3 |

|
| content 1
|

所以基本上我有一个菜单,当您选择菜单语音时,会显示相关的子菜单,当您选择子菜单语音时,会显示相关内容。

路由系统遵循菜单结构,所以如果你去 /voice1/submenu1 你应该显示 content 1,如果你点击 submenu2 然后你去 /voice1/submenu2 和显示 content 2 等等等等。

当用户登录时,我不想呈现一个空页面,但我希望路由已经填充了默认组件(在本例中为 voice 1submenu 1, content 1), 但我不知道该怎么做。现在我解决了在我的路由拦截器中添加这个问题:

router.beforeEach((to, from, next) ⇒ {
const token = store.getToken();

const tokenIsValid = validateToken(token);
const routeDoesntNeedAuth = routeWithoutAuth.indexOf(to.fullPath) > -1;

if (tokenIsValid || routeDoesntNeedAuth) {
if (to.fullPath === '/') {
next('/voice1/submenu1'); // <- this line does the trick
}

next();
} else {
next('/login');
}
});

但我确信有更好的方法来做到这一点。我的路线系统如下:

export default new Router({
mode: 'history',
routes: [
{
path: '/',
component: AppWrapper,
children: [
{
path: '/voice1',
components: {
default: PageWrapper,
subMenu: VoiceFirstSubMenu,
},
children: [
{
path: 'submenu1',
components: {
mainContent: ContentOne,
},
},
{
path: 'submenu2',
components: {
mainContent: ContentTwo,
},
},
{
path: 'submenu3',
components: {
mainContent: ContentThree,
},
},
],
},
],
},
{
path: '/login',
component: Login,
},
],
});

我该如何解决这个问题?

Divine 的问题是正确的,问题是我有这行代码将我所有的路由重定向到 /:

this.$router.push('/');

在包含整个应用程序的包装器组件中。删除该行后,一切正常。

最佳答案

您可以在路由配置中使用redirect属性来重定向任何路由

每当 / 路由被调用时,vuejs 将自动重定向到 /voice1/submenu1

routes: [
{
path: '/',
redirect: '/voice1/submenu1', <---- / route will be redirected to /voice1/submenu1
component: AppWrapper,
children: [
...
]
},
]

关于javascript - vue-router 的默认子路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816603/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com