[Vuejs]-Vue Router adds # (hash) after calling router.push() in "history" mode

1👍

Instead of creating a separate route that points to the same component, use an optional parameter on one route:

export default new VueRouter({
  mode: "history",
  routes: [
    {
      path: "/:league?", // `?` makes `league` OPTIONAL
      component: Home,
      props: true,
      name: "home"
    }
  ]
});

And if you need to use $router.push() to change only the parameter value, you could omit the name or path:

<button @click="$router.push({ params: { league: 'myLeague' } })">
  Go to My League
</button>

Note if the UI is intended to be a link, it might be best to use router-link, which avoids the Avoided redundant navigation to current location console warning:

<router-link :to="{ params: { league: 'myLeague' } }">Go to My League</router-link>

demo

👤tony19

2👍

I found several bugs:

  1. Check how your router is connected and configured:
const routes = [
  { path: '/', name: 'Home', component: Home },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router
  1. You need to write $router, when you call a push.
  2. You can’t write a name like router.history.current.name, because you will go to the same page. So state explicitly: home/league.
  3. Better not use one component to output different routes, this is not very good. But you can use child routes.

Leave a comment