Search code examples
vuejs3vue-router

In vue3, why router.currentRoute and router.currentRoute.value printed value different?


When I use the address to enter the /npc page or refresh the page in the /npc page, I encounter the following situation.

Code:

router.beforeEach(async () => {
  console.log(router.currentRoute, router.currentRoute.value)
})

output:

enter image description here

Ref has value, why not print directly?

I'm trying to figure out what happened and why it happened.


Solution

  • When you expand a property of an object that's been console logged it's going to show you the live (current) value, not the value it actually might have been at the exact time of logging. See the MDN documentation on logging objects with console.log

    As the documentation suggests, a workaround is to deep-clone the object before logging. In your case:

    console.log(
      JSON.parse(JSON.stringify(router.currentRoute)),
      JSON.parse(JSON.stringify(router.currentRoute.value))
    )
    

    This should show the same value.

    FYI, you don't mention why you're wanting to log router.currentRoute inside the navigation guard, but generally inside a guard you're interested in the "from" route and the "to" route, both of which are provided for you as parameters. See Vue Router documentation

    router.beforeEach(async (to, from) => {
      console.log(from)
    })
    

    This gives you the same info without worrying about the value changing on you in the console.