Error get current route name same path in vuejs

Viewed 16

I define route name in route.js

...

    const routes = [
        {
            path: "/region-price/:state_id?",
            component: RegionPrice,
            name: "region-price"
        },
        {
            path: "/region-price/city_info",
            component: RegionPrice,
            name: "region-price-city"
        },
        {
            path: "/region-price/area_info",
            component: RegionPrice,
            name: "region-price-area"
        }
    ];

...

And .vue file

...
computed: {
   currentRouteName() {
      return this.$route.name;
   }
},
created() {
   console.log(this.currentRouteName);
},
...

This is my result

https://test.com/region-price/1 -> route name is region-price ok

https://test.com/region-price/city_info -> route name region-price-city, but result is region-price

https://test.com/region-price/city_info?city_id=1 -> route name region-price-city, but result is region-price

https://test.com/region-price/area_info -> route name is region-price-area, but result is region-price, too

1 Answers

All these routes use the same component and you're only console logging at component's creation, which only happens one time for as long as you're routing to the same component. That's part of the magic of a framework like Vue, it doesn't recreate the whole DOM every time something changes, it only updates what's necessary. A better idea would be to display currentRouteName in your template somewhere. You should see it updating to the correct value.

Related