[Vuejs]-Why does the router link not work the first time?

0👍

You have duplicate routes in your config – the path / is used on 2 routes. You should fix this.

To prevent unauthorized users to see your protected pages you can add a global navigation guard to your router through the beforeEach hook:

import VueRouter from 'vue-router';

const routes = [
  {
    path: "/",
    component: () => import("layouts/MainLayout"),
    meta: { requireAuth: true },
    children: [
      {
        path: "",
        component: () => import("pages/Index"),
      },

      {
        path: "logs",
        component: () => import("pages/Logs"),
        meta: { admin: true }
      }
    ]
  },
  {
    path: "/login",
    component: () => import("layouts/AuthLayout"),
    children: [
      {
        path: "",
        component: () => import("pages/Auth"),
      },
      {
        path: "/register",
        component: () => import("pages/Register"),
      }
    ]
  }
];

const router = new VueRouter({
  routes
});

router.beforeEach((to, from, next) =>
{
  if (to.matched.some(route => route.meta.requireAuth))
  {
    if (userNotLogged) next('/login');
    else next();
  }
  else next();
});


export default router;

You may also consider reading a more verbose tutorial, e.g. https://www.digitalocean.com/community/tutorials/how-to-set-up-vue-js-authentication-and-route-handling-using-vue-router

Leave a comment