I have a Vue 2.x application and I'm using vue-router to handle the routing.
In some scenario, I have to display directly a children vue. My template is the following:
| voice 1 | voice 2 | voice 3 |
| submenu 1 | submenu 2 | submenu 3 |
|
| content 1
|
So basically I have a menu, when you select a menu voice the relative submenu is displayed, when you select a submenu voice the relative content is displayed.
The routeing system follows the menu structure so if you go to /voice1/submenu1
you should display the content 1
, if you click to submenu2 then you go to /voice1/submenu2
and display content 2
and so on and so forth.
When the user logs in, I don't want to present an empty page, but I want the route to be already populated with default components (in this case voice 1
, submenu 1
, content 1
), but I don't know how to do that. For now I solved the problem adding this in my route interceptor:
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');
}
});
But I'm sure there's a better way to do this. My route system is the following:
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,
},
],
});
How can I solve this?
Divine's question is correct, the problem was that I had this line of code that was redirecting all my routes to /
:
this.$router.push('/');
In a wrapper component that contains the whole application. Once removed that line everything worked perfectly.
You can use redirect
property in the route config
to redirect any route
whenever /
route is invoked vuejs will automatically redirect to /voice1/submenu1
routes: [
{
path: '/',
redirect: '/voice1/submenu1', <---- / route will be redirected to /voice1/submenu1
component: AppWrapper,
children: [
...
]
},
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With