Search code examples
javascriptvue.jsurl-parameters

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.


Solution

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