javascriptvue.jsvue-router4

Vue-Router render the component but doesn't change the url


import { createMemoryHistory, createRouter } from "vue-router";
import { AuthUser } from "../../auth/user";

const routes = [
  {
    path: "/",
    component : () => import("../components/Home/Home.vue"),
    beforeEnter : (to, from, next)=>{
      if(!AuthUser()){
        next({path : "/signup"})
      }else{
        next()
        return ""
      }
    }
  },
  {
    path: "/signup",
    component : () => import("@/components/Signup/Signup.vue"),
  }
];

const router = createRouter({
  history: createMemoryHistory(),
  routes,
});

export default router
 

I don't know why when I open "/" , the component signup it's show but url "http://localhost:3000/ " doesn't change at all.

The component it's show perfectly, it's the url the problem.

AuthUser always return false for now.


Solution

  • This happens because you use createMemoryHistory() as a history mode which is not browser-compatible but used for tests and server-side rendering, you need to use createWebHistory() instead which leverages the browser's history.

    import { createWebHistory, createRouter } from 'vue-router';
    import { AuthUser } from "../../auth/user";
    
    const routes = [
      {
        path: "/",
        component : () => import("../components/Home/Home.vue"),
        beforeEnter : (to, from, next) => {
          if (!AuthUser()) {
            next({path : "/signup"});
          } else {
            next();
          }
        }
      },
      {
        path: "/signup",
        component : () => import("@/components/Signup/Signup.vue"),
      }
    ];
    
    const router = createRouter({
      history: createWebHistory(),
      routes,
    });
    
    export default router;