5

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.

samayo
  • 16,163
  • 12
  • 91
  • 106
Chirag Chaudhari
  • 1,617
  • 3
  • 14
  • 20

4 Answers4

6

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

Rob
  • 518
  • 1
  • 3
  • 18
samayo
  • 16,163
  • 12
  • 91
  • 106
5

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.

InSync
  • 4,851
  • 4
  • 8
  • 30
Nancy Brown
  • 360
  • 3
  • 2
0

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]);
    } 
bbsimonbb
  • 27,056
  • 15
  • 80
  • 110
-2

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

hannad rehman
  • 4,133
  • 3
  • 33
  • 55
  • i am not using vue-router. and $route is not present in my case as it is created when using vue router. thats what i am asking is there any way around it. – Chirag Chaudhari Dec 12 '17 at 12:56