[javascript] How can I get query parameters from a URL in Vue.js?

How can I fetch query parameters in Vue.js?

E.g. http://somesite.com?test=yay.

Can’t find a way to fetch or do I need to use pure JS or some library for this?

This question is related to javascript vue.js vue-router url-parameters

The answer is


Without vue-route, split the URL

var vm = new Vue({
  ....
  created()
  {
    let uri = window.location.href.split('?');
    if (uri.length == 2)
    {
      let vars = uri[1].split('&');
      let getVars = {};
      let tmp = '';
      vars.forEach(function(v){
        tmp = v.split('=');
        if(tmp.length == 2)
        getVars[tmp[0]] = tmp[1];
      });
      console.log(getVars);
      // do 
    }
  },
  updated(){
  },

Another solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:

var vm = new Vue({
  ....
  created()
  {
    let uri = window.location.search.substring(1); 
    let params = new URLSearchParams(uri);
    console.log(params.get("var_name"));
  },
  updated(){
  },

You can get By Using this function.

console.log(this.$route.query.test)

If your url looks something like this:

somesite.com/something/123

Where '123' is a parameter named 'id' (url like /something/:id), try with:

this.$route.params.id

More detailed answer to help the newbies of VueJS:

  • First define your router object, select the mode you seem fit. You can declare your routes inside the routes list.
  • Next you would want your main app to know router exists, so declare it inside the main app declaration .
  • Lastly they $route instance holds all the information about the current route. The code will console log just the parameter passed in the url. (*Mounted is similar to document.ready , .ie its called as soon as the app is ready)

And the code itself:

<script src="https://unpkg.com/vue-router"></script>
var router = new VueRouter({
    mode: 'history',
    routes: []
});
var vm =  new Vue({
    router,
    el: '#app',
    mounted: function() {
        q = this.$route.query.q
        console.log(q)
    },
});

As of this date, the correct way according to the dynamic routing docs is:

this.$route.params.yourProperty

instead of

this.$route.query.yourProperty

Try this code

 var vm = new Vue({
     created()
     {
       let urlParams = new URLSearchParams(window.location.search);
           console.log(urlParams.has('yourParam')); // true
           console.log(urlParams.get('yourParam')); // "MyParam"
     },

Another way (assuming you are using vue-router), is to map the query param to a prop in your router. Then you can treat it like any other prop in your component code. For example, add this route;

{ 
    path: '/mypage', 
    name: 'mypage', 
    component: MyPage, 
    props: (route) => ({ foo: route.query.foo })  
}

Then in your component you can add the prop as normal;

props: {
    foo: {
        type: String,
        default: null
    }
},

Then it will be available as this.foo and you can do anything you want with it (like set a watcher, etc.)


You can use vue-router.I have an example below:

url: www.example.com?name=john&lastName=doe

new Vue({
  el: "#app",
  data: {
    name: '',
    lastName: ''
  },
  beforeRouteEnter(to, from, next) {
      if(Object.keys(to.query).length !== 0) { //if the url has query (?query)
        next(vm => {
         vm.name = to.query.name
         vm.lastName = to.query.lastName
       })
    }
    next()
  }
})

Note: In beforeRouteEnter function we cannot access the component's properties like: this.propertyName.That's why i have pass the vm to next function.It is the recommented way to access the vue instance.Actually the vm it stands for vue instance


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to vue.js

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Center content vertically on Vuetify Vue.js get selected option on @change Using Environment Variables with Vue.js did you register the component correctly? For recursive components, make sure to provide the "name" option Vue 'export default' vs 'new Vue' How can I go back/route-back on vue-router? Change the default base url for axios How to reference static assets within vue javascript How to change port number in vue-cli project

Examples related to vue-router

How can I go back/route-back on vue-router? Vuejs: Event on route change How to VueJS router-link active style How to add external JS scripts to VueJS Components VueJs get url query Do we have router.reload in vue-router? How to pass a value from Vue data to href? How to set URL query params in Vue with Vue-Router Vue-router redirect on page not found (404) Can vue-router open a link in a new tab?

Examples related to url-parameters

What is the difference between URL parameters and query strings? RestTemplate: How to send URL and query parameters together How can I get query parameters from a URL in Vue.js? How can I get the named parameters from a URL using Flask? How to get a URL parameter in Express? PHP check if url parameter exists Pass Hidden parameters using response.sendRedirect() How to convert URL parameters to a JavaScript object? How to replace url parameter with javascript/jquery? Username and password in https url