Hendrik Jan
Hendrik Jan

Reputation: 4908

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

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?

Upvotes: 26

Views: 49273

Answers (1)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

You could use composable function useRoute :

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

setup(){
   const route=useRoute();

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

Upvotes: 54

Related Questions