Showing posts with label URL. Show all posts
Showing posts with label URL. Show all posts

Saturday, July 2, 2022

Vue.js How to get query parameter from URL

In this tutorial, we are going to learn how we can get the query parameter from URL.

let's look into the sample example.

http://360learntocode.com?username=test

Using Vue Router:

Here, we want to get the username query parameter. In Vue.js there is an elegant way to get query parameters. If we are using the router then we can get the parameter inside the vue.js component as below.

let username =  this.$route.query.username

Which gives the username value. Another way to get parameters with the router is

let username = this.$route.params.username

Using Javascript URLSearchParams :

We can use URLSearchParams() method which helps to work with the query string of the URL. We can use this inside our vue.js component methods as below.

 methods: {
    getUsername() {
      const queryString = window.location.search;
      if (queryString) {
        const urlParams = new URLSearchParams(queryString);
      	if (urlParams.has('username')) {
          return urlParams.get('username');
        }
      }
      return "";
    }
  }

Or

 methods: {
    getUsername() {
      const queryString = window.location.href;
      if (queryString) {
      	let urlString = queryString.split('?')[1]
        const urlParams = new URLSearchParams(urlString);
      	if (urlParams.has('username')) {
          return urlParams.get('username');
        }
      }
      return "";
    }
  }
Share: