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?
We can use this. $router. currentRoute. path property in a vue router component to get the current path.
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.
/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.
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...
You could use composable function useRoute
:
import {useRoute} from 'vue-router'
import {computed} from 'vue'
...
setup(){
const route=useRoute();
const path = computed(() =>route.path)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With