user12009061
user12009061

Reputation:

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.

Upvotes: 11

Views: 37231

Answers (4)

Pri Nce
Pri Nce

Reputation: 711

This is so simple

// app.js
Vue.prototype.$url= window.location.origin;

// in component
console.log(this.$url)

output: https://stackoverflow.com

Upvotes: 0

Ricardo Martins
Ricardo Martins

Reputation: 5993

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

Upvotes: 2

msayubi76
msayubi76

Reputation: 1668

Simple and easy way to get baseUrl in VueJs is

var baseUrl = window.location.origin

Upvotes: 9

Matthias
Matthias

Reputation: 4163

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"
  }
}

Location Origin.

Upvotes: 14

Related Questions