Best way to get current route in Vue3 and Vue-router?
Asked Answered
M

1

26

I am trying to get the current path (something like "https://example.com/some/path") with Vue3 and Vue-router.

Before, when using Vue2, I could get the current route using:

    // works with vue 2.x with composition-api, but not with vue 3.x
    setup(_, ctx) {
        const path = computed(() => ctx.root.$route.path)

but in Vue3 it is not possible to use ctx.root (as stated by Evan You here).
So what is the preferred way to get the current route with Vue3?

Mien answered 1/2, 2021 at 8:40 Comment(0)
C
53

You could use composable function useRoute :

import {useRoute} from 'vue-router'
import {computed} from 'vue'
...

setup(){
   const route=useRoute();

   const path = computed(() =>route.path)
}

Candor answered 1/2, 2021 at 8:43 Comment(8)
How to do that in the options api?Atony
@PetarVasilev you could use this.$route.pathCandor
I am trying to access this.$route.name but it is the same. name is always undefined even though in the global instance of vue-router current route is correct. path is always / even though I am on another page. Any ideas?Atony
@PetarVasilev can you show how did you use it? and how did configure the router?Candor
It turns out there was a problem with my computer when I restarted it started working.Atony
Actually, there was another problem. Vue router was not ready. I had to wrap application.mount('#app'); in router.isReady().then(...)Atony
Please create a new question describing the issue and let me knowCandor
That solved it so no point in in question. Hopefully, people can find it here.Atony

© 2022 - 2024 — McMap. All rights reserved.