[Vuejs]-Vue router guard triplicating navigation

0👍

I think that it has something to do with your router path:

  {
    path: "*",
    redirect: "/login",
  },

I have used Vue Router several times, but since I hadn’t used wildcards before, I built a simplified Vue 2 CLI test application.

My router:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import Home from '@/components/stackoverflow/router-wildcard-match/Home'
import RouteOne from '@/components/stackoverflow/router-wildcard-match/RouteOne'
import RouteTwo from '@/components/stackoverflow/router-wildcard-match/RouteTwo'
import WildCard from '@/components/stackoverflow/router-wildcard-match/WildCard'

const routes = [
  {
    path: '/*',
    name: 'wildcard',
    component: WildCard
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
  },
  {
    path: '/routeone',
    name: 'routeOne',
    component: RouteOne,
  },
  {
    path: '/routetwo',
    name: 'routeTwo',
    component: RouteTwo,
  },
]

export default new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

and my navbar component that routes programmatically:

<template>
  <div class="navbar-sandbox">
    <nav class="navbar navbar-expand-md navbar-light bg-light">
      <ul class="navbar-nav mr-auto">
        <li class="nav-item active">
          <a class="nav-link" href="#" @click.prevent="navigate('home')">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#" @click.prevent="navigate('routeone')">RouteOne</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" href="#" @click.prevent="navigate('routetwo')">RouteTwo</a>
        </li>
      </ul>
    </nav>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        //currentRoute: 'home',
        currentPath: 'home'
      }
    },
    methods: {
      // NOTE: Using route names work regardless of having wildcard path
      // navigate(route) {
      //   if (route !== this.currentRoute) {
      //     this.currentRoute = route;
      //     this.$router.push({ name: route });
      //   }
      // },
      navigate(path) {
        if (path !== this.currentPath) {
          this.currentPath = path;
          this.$router.push({ path: path });
        }
      }
    }
  }
</script>

As you can see in my code comments, when I programmatically route via the route names, it works even with having a wildcard path, but when I route via the actual route path, the routes are all intercepted by the wildcard.

My wildcard path is a bit different that yours, /* vs *.

Leave a comment