Vue Js Get Current Url/Route – To get the current URL in Vue.js, you can access the window.location.href
property, which returns the current URL as a string. You can use this property in your Vue component methods or computed properties to get the current URL and use it for various purposes, such as redirecting to another page, manipulating the URL parameters, or sending the URL to the server.
To access the current URL, you can create a method or computed property in your Vue component that returns window.location.href
, or you can use it directly in your component’s template using the {{ }}
interpolation syntax
Vue js get Current Url Syntax:
this.currentUrl ='Current Url: '+ window.location.href;
How to get Vue Js current Url
The code you provided is a Vue.js component that displays the current URL using the window.location.href
property. Here’s a breakdown of the code:
- The HTML part creates a
div
element with anid
ofapp
and ap
element that displays the current URL using Vue.js data binding syntax. - The JavaScript part initializes a new Vue.js instance and specifies the
el
property as#app
, which connects the Vue.js instance to thediv
element with theapp
ID in the HTML. - The
data
property defines an object with a single propertycurrentUrl
, which is initialized with the current URL obtained fromwindow.location.href
. - The
{{ currentUrl }}
syntax in thep
element binds thecurrentUrl
property of the Vue.js data object to the text content of thep
element.
Vue Js Current URl Example
<div id="app">
<p>Current Url is {{ currentUrl}}</p>
</div>
<script type="module">
const app = new Vue({
el: "#app",
data() {
return {
currentUrl: window.location.href
};
}
})
</script>