'How to get baseURL inside Vuejs method using vue router?
I have a method where need to create a string which consists of
base URL /get-it and some random generated string?
methods:{
GenerateURL(){
...
}
}
How can be it achieved? How can I either get base URL or /get-it with vue router but without navigating to that /get-it page which is empty? I just need to use it as a string inside the component.
Solution 1:[1]
From the docs:
$route.path
type: string
A string that equals the path of the current route, always resolved as an absolute path. e.g. "/foo/bar"
So in your case you could do something like this:
methods:{
GenerateURL(){
var fullUrl = window.location.origin + this.$route.path + "/get-it/yourRandomString"
}
}
Solution 2:[2]
Simple and easy way to get baseUrl in VueJs is
var baseUrl = window.location.origin
Solution 3:[3]
Given https://mywebsite.com/some/vue/route
import router from "@/router";
console.log(window.location.origin) // https://mywebsite.com
console.log(router.currentRoute.value.fullPath) // /some/vue/route
Solution 4:[4]
This is so simple
// app.js
Vue.prototype.$url= window.location.origin;
// in component
console.log(this.$url)
output: https://stackoverflow.com
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Matthias |
| Solution 2 | msayubi76 |
| Solution 3 | Ricardo Martins |
| Solution 4 | Pri Nce |
