Search code examples
vue.jsvuejs3vue-routervue-composition-apivue-script-setup

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?


Solution

  • You could use composable function useRoute :

    import {useRoute} from 'vue-router'
    import {computed} from 'vue'
    ...
    
    setup(){
       const route=useRoute();
    
       const path = computed(() =>route.path)
    }