Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 683
Hendrik Jan Avatar asked Feb 01 '21 08:02

Hendrik Jan


People also ask

How do I get the current route on my vue router?

We can use this. $router. currentRoute. path property in a vue router component to get the current path.

How do I watch my vue route?

To listen for route change events with Vue. js and Vue Router, we can watch the $route object in our component. to watch the $route in our component. We set deep to true to watch for all changes in the $route object's contents.

How do I use my vue3 vue router?

/src/router/index.js Notice that we create our routes in an array, where we specify for each route a few important items: Path - the URL path where this route can be found. Name - An optional name to use when we link to this route. Component - Which component to load when this route is called.

How do I get a current URL on vue?

if you are working with plan vuejs without using vue js route then you can get with window object. but if you are using vue js route then you can also get with route object. so it is a very simple way we can get current url. I give you bellow both example, just see it and ut it those you require...


Video Answer


1 Answers

You could use composable function useRoute :

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

setup(){
   const route=useRoute();

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

like image 140
Boussadjra Brahim Avatar answered Sep 30 '22 13:09

Boussadjra Brahim