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

ghz 8months ago ⋅ 124 views

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?

Answers

In Vue.js, you can access query parameters using the this.$route.query object. This object contains key-value pairs of the query parameters present in the current route.

Here's how you can fetch query parameters in a Vue.js component:

export default {
  mounted() {
    // Access the query parameters
    const queryParams = this.$route.query;

    // Access individual query parameters
    const testParam = queryParams.test;

    console.log('Test parameter:', testParam);
  }
}

In this example, this.$route.query is used to access all the query parameters in the current route. You can then access individual query parameters by their keys, such as test in this case.

Make sure to import the vue-router library and configure your routes properly for this to work. The this.$route object is provided by the Vue Router and gives you access to information about the current route, including query parameters.