URL Query Parameters with JavaScript, Vue 2 and Vue 3

Dan Pastori avatar
Dan Pastori September 6th, 2022

This is a quick little post that goes through how to get and set URL parameters with vanilla JavaScript and VueJS. I’m going to provide both examples, JavaScript and in the context of VueJS. There are scenarios where you might not be using VueJS and it’s extremely helpful to access these parameters through JavaScript.

Working with URL parameters helps you deep link within your application, set filters, and work with dynamic content. Even if you aren’t building a single page app, this tutorial will help you preset filters and get share the deep links with others. What I’m referring to with URL parameters is any of the GET variables that can be set through a filter or a deep link. For example, let’s say we want to filter tickets by location, type, and user. We’d want to share this link, or book mark it for easy access. Our URL would look like: /tickets?location=Milwaukee&user=3&type=support.

Let’s take a look on how we’d create that URL and access those parameters with JavaScript and VueJS.

Setting URL Parameters with JavaScript

We will start with setting URL parameters with JavaScript. This is the logical place to begin, you must have a URL with parameters before accessing them. The goal of this tutorial is to set these parameters without a hard page reset. Otherwise, you’d lose your filter every time and that wouldn’t be too productive. The vanilla JavaScript method works in Vue as well if you are not using Vue Router (i.e. InertiaJS, Vue components in HTML, etc.).

The key to setting URL parameters is the window.history.pushState() method. What this does is push to the window history, similar to a single page app router.

The pushState() method accepts 3 parameters. The first parameter is the “state”. This parameter contains the object of actual state, such as page_id, that the user is on. You’d think this is where we’d set the “state” for our URL parameters. However, we want our parameters to be a part of the URL, not stored in a JavaScript variable.

The second parameter is weird and is actually not used anymore. The best advice is to pass an empty string according to the documentation. Weird, but true.

Finally, the third parameter is the URL we are pushing on to the history. With this parameter, we can pass a new URL, different than the one we are on, or we can update parameters. Exactly what we need to do. Let’s use our example above for our /tickets url and set the location, user, and type query parameters:

const searchURL = new URL(window.location);
searchURL.searchParams.set('location', 'Milwaukee');
searchURL.searchParams.set('user', 3);
searchURL.searchParams.set('type', 'support');

window.history.pushState({}, '', searchURL);

So what we did was created a new URL() object and set it to the current page. From there, we set the searchParams on that object which will build our proper GET URL. Finally, we pushed empty state to the history with the third parameter being the new URL (the current url with the additional parameters). When you run the above code, you should see the URL in the browser window change to /tickets?location=Milwaukee&user=3&type=support. Exactly what we want!

Now when you set the search parameters, they will probably come from an input box, select field, or other form field when building your filter. The inputs can be computed values, grabbed from inputs, etc. A tip would be to update the url oninput or onchange so whenever the user selects a new value, the query parameter changes and is represented in the URL.

Once we have our inputs set, we can read from them and set our defaults to build out our functionality.

Accessing URL Parameters in JavaScript

At this point, we are able to dynamically set our URL with filters defined by the user. We can take that URL and save it as a bookmark or share it with a colleague to deep link to a predefined set of filters. Whatever the use case, we need to be able to read in these variables from JavaScript.

Using the filters above, I want to create a simple method that presets some local variables from the ones defined in the URL. I call this method when the document is ready, or in a mounted() hook from within VueJS. Make sure you run this method on set up. Let’s take a look at the method I named setQueryStringDefaults().

let locationFilter = '';
let userFilter = '';
let typeFilter = '';

setQueryStringDefaults(){
    let queryString = window.location.search;
    let urlParams = new URLSearchParams(queryString);
    
    if( urlParams.has('location') ){
        locationFilter = urlParams.get('location');
    }

    if( urlParams.has('user') ){
        userFilter = urlParams.get('user');
    }

    if( urlParams.has('type') ){
        typeFilter = urlParams.get('type');
    }
}

Just for clarity, I added a few extra variables before the method to show what we are setting. For this method, we will be using the [window.location.search](<http://window.location.search>) variable. This method contains our query string that is present in the URL. We then take the query string and break it into parts using the URLSearchParams() object. From there we check to see if the object contains each of the variables we are looking for with the urlParams.has()method. If it does, we call urlParams.get() to retrieve the value and initialize our filter variables.

It’s pretty slick and can add some really powerful functionality to your app. Let’s take a look on how to do this with Vue Router if you are using VueJS. Like I mentioned, you don’t have to use Vue Router, the above example works in any JavaScript application.

Setting URL Query Parameters with Vue Router

Above we pretended we had a /tickets route that accepted location, user, and type variables. Let’s say we are within a Vue app that’s using Vue Router and we want to update these filters based on what the user selects as a filter. To do this, whenever filter updates, run the following code:

this.$router.push({ path: '/tickets', params: { location: 'Milwaukee', user: 3, type: 'support' } })

That’s it! What this code does is push on to the underlying history state (same as we did in the vanilla JavaScript example) with the query parameters set. The router.push method takes an object that contains parameters describing the route being navigated. You could also use name: tickets if your route was named tickets as well. Vue Router is set up perfect for working with URL query variables since the whole purpose is to load dynamic data through the URL.

Composition API

To use the above example with the Composition API, you’d have to make sure to use the useRouter() composable method:

import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter();

    function updateFilters(query) {
      router.push({
        name: 'search',
        query: {
          location: 'Milwaukee',
          user: 3,
          type: 'support'
        },
      })
    }
  }
}

Let’s take a look at how to access query parameters with Vue Router.

Accessing URL Query Parameters with Vue Router

When using Vue Router, to access URL query parameters, you can access the route object using this.$route.query:


export default {
    data(){
        location: '',
        user: '',
        type: ''
    },

    mounted(){
        this.location = this.$route.query.location;
        this.user = this.$route.query.user;
        this.type = this.$route.query.type;
    }
}

In the example above, I set our local filters from our URL by accessing the this.$route.query object. One place I always get confused is the difference between this.$route.query and this.$route.params. The this.$route.query method contains the URL Query parameters used for filtering a certain endpoint. The this.$route.params accesses a parameter within the URL such as /user/3 . The 3 would define the user and be accessed through this.$route.params.user. It’s a named part of the URL.

Composition API

Using the composition API, the above access would look like:

import { ref } from 'vue';
import { useRoute } from 'vue-router'

export default {
  setup() {
    const location = ref('');
    const user = ref('');
    const type = ref('');

    const route = useRoute()

    location.value = route.query.location;
    user.value = route.query.location;
    type.value = route.query.value;
  },
}

Conclusion

Setting and getting url parameters in JavaScript, Vue 2 and Vue 3 is a really quick way to make sharable, easily accessible deep links within your application. This process works great for large forms that need a lot of filters that you need repeatable or sharable.

If you have any questions, feel free to reach out on Twitter (@danpastori). If you want more tutorials in your inbox, sign up for our mailing list.

Support future content

The Ultimate Guide to Building APIs and Single-Page Applications with Laravel + VueJS + Capacitor book cover.

Psst... any earnings that we make off of our book is being reinvested to bringing you more content. If you like what you read, consider getting our book or get sweet perks by becoming a sponsor.

Written By Dan

Dan Pastori avatar Dan Pastori

Builder, creator, and maker. Dan Pastori is a Laravel certified developer with over 10 years experience in full stack development. When you aren't finding Dan exploring new techniques in programming, catch him at the beach or hiking in the National Parks.

Like this? Subscribe

We're privacy advocates. We will never spam you and we only want to send you emails that you actually want to receive. One-click unsubscribes are instantly honored.