Chirag Chaudhari
Chirag Chaudhari

Reputation: 1827

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.

Upvotes: 5

Views: 5276

Answers (4)

Nancy Brown
Nancy Brown

Reputation: 418

You can get the URL parameters by using window.location.search:

const queryString = window.location.search;
console.log(queryString);
// ?product=troussers&color=black&newuser&size=s

For parsing parameters of the query string, use URLSearchParams:

const urlParams = new URLSearchParams(queryString);

For more info, read this tutorial.

Upvotes: 5

samayo
samayo

Reputation: 16495

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')

Upvotes: 6

bbsimonbb
bbsimonbb

Reputation: 28992

We don't use vue router for the moment either. We use the following script to parse args.

    var args = {};

    var argString = window.location.hash;
    //everything after src belongs as part of the url, not to be parsed
    var argsAndSrc = argString.split(/src=/);
    args["src"] = argsAndSrc[1];
    //everything before src is args for this page.
    var argArray = argsAndSrc[0].split("?");
    for (var i = 0; i < argArray.length; i++) {
        var nameVal = argArray[i].split("=");
        //strip the hash
        if (i == 0) {
            var name = nameVal[0];
            nameVal[0] = name.slice(1);
        }
        args[nameVal[0]] = decodeURI(nameVal[1]);
    } 

Upvotes: 0

hannad rehman
hannad rehman

Reputation: 4331

Route properties are present in this.$route.

this.$router is the instance of router object which gives the configuration of the router.

You can get the current route query using this.$route.query

Upvotes: -2

Related Questions