2
votes

I don't know I'm about quite Vue, spent a day learning all hooks routes, tried throug regular hooks created, mounted and it still gives me null. Here is my component App where all other components are plugged in. I'm calling here mounted hook, so basically it totally rendered this component, and we have a path + I wrapped evrythin in $nextTick just to be sure and it still returns me null name of a current router if I come to the website not from main url, but from children as for instance url/boys. I gave up long time ago getting this name of a router in children component where I need it, thought alright I'll just path it to children <the-nav/> that's where I need it. But it doesnt work event in parent and I need only name of a current router when I enter the website. That's it, sounds easy but went throught hell.

<template>
      <div id="app">
        <the-header/>
        <the-nav/>
        <div id="app__inner">
          <transition name="fade" mode="out-in">
            <router-view />
          </transition>
        </div>
      </div>
    </template>

    <script>
      import TheHeader from "@/components/TheHeader.vue";
      import TheNav from "@/components/TheNav.vue"

      export default {
        components : {
          TheHeader,
          TheNav
        },
        mounted()
        {
          this.$nextTick(() => {
            console.log(this.$router.currentRoute.name);
          })
        }
      }
    </script>
2
have you tried using this.$route instead of this.$router ?procoib
this.$router.currentRoute.name is the same as this.$route.name There is no need for $nextTick - if you are already inside this hook then the route has already been changed.IVO GELOV
Can you try console.log(this.$router.currentRoute);?Anatoly

2 Answers

0
votes

You can actually use the exposed router functions inside this befoureRouteEnter function, used like so:


beforeRouteEnter (to, from, next) {
    console.log(to.name);
    next();
  },

Please read some documentation on router Navigation guards: https://router.vuejs.org/guide/advanced/navigation-guards.html

0
votes

Make sure you have the name set on the router, otherwise name will be undefined. For example...

const routes = [
  { 
    path: "/", 
    component: Home, 
    name: "Home"  // Make sure route is named
  },
];

Then in component you should be able to access the name in mounted hook, without nextTick (like mentioned in comment):

mounted() {
  alert(`Route name is: ${this.$route.name}`);
}

DEMO