Currently, I am working on a Vue 2.x application and utilizing vue-router for routing purposes.
In certain situations, I need to directly display a child vue. The template structure is as follows:
| voice 1 | voice 2 | voice 3 |
| submenu 1 | submenu 2 | submenu 3 |
|
| content 1
|
The concept is simple - upon selecting a menu voice, the corresponding submenu is shown; similarly, selecting a submenu voice displays the associated content.
The routing system mirrors the menu structure so that if you navigate to /voice1/submenu1
, it should display content 1
. By clicking on submenu2, you are directed to /voice1/submenu2
to show content 2
, and so forth.
Upon user login, rather than presenting an empty page, I prefer having default components preloaded in the route (such as voice 1
, submenu 1
, content 1
). However, I am uncertain about the optimal approach. Currently, I have addressed this by adding the following snippet 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');
}
});
While this solves the immediate issue, I believe there could be a more efficient way to achieve the desired outcome. Here is how my route system is structured:
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,
},
],
});
If anyone has insights on enhancing this process, please share your thoughts!
Recently, Divine raised a crucial question which pointed out that a specific line of code was causing redirection of all routes to /
:
this.$router.push('/');
This misstep was within a wrapper component containing the entire application. Once I removed that line, everything functioned flawlessly.