Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get URL parameters in JavaScript?

I'm using Vue, but I'm not using vue-router.

How can I get URI parameters?

I found one way to get URI by using root el property.

screenshot

But is there any proper way to get the parameters as I want to send them to backend and get a response from server and display it.

like image 953
Chirag Chaudhari Avatar asked Sep 11 '25 04:09

Chirag Chaudhari


1 Answers

Since you are not using vue-router, I don't think you'll be able to access your params. So your only chance is to use the URL api as:

const url = new URL(window.location.href); 
const getParam = url.searchParams.get('foo'); 

This will give you the value of foo in ?foo=bar


Alternatively, you can do something like this.

new Vue({
 el: '#app',
 
 data () {
   return {
     params: window.location.href.substr(window.location.href.indexOf('?'))
   }
 },
 
 methods: {
   getParam (p) {
     let param = new URLSearchParams(this.params);
     if(param.has(p)){
       return param.get(p)
     }else{
       false
     }
   }
 },
})

Now, just get the param using getParam('foo')

like image 116
samayo Avatar answered Sep 13 '25 17:09

samayo