4

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.

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

1 Comment

thank you for the answer. I thought there is any other way around it.
6

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.

2 Comments

That link is unfortunately dead.:/
I removed /m and now it is no longer dead.
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]);
    } 

Comments

-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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.