How to Get Query Parameters from a URL in Vue.js
Read this short Vue.js tutorial and learn a super easy method that is used to get the query parameters from the URL. Also, read about query parameters.
Detecting the query string parameters in <kbd class="highlighted">Vue.js</kbd> is quite simple. Let’s discuss it together and find a perfect solution in this tutorial. You can get the query string parameter simply using Vue Router.
Let’s discuss the following example. Consider you have this path:
https://w3docs.com?test=yay
In the given URL the key is <kbd class="highlighted">test</kbd> and the value is <kbd class="highlighted">yay</kbd>.
Inside a Vue component, you can access the query params by using the key like this:
// Options API
console.log(this.$route.query.test) // outputs 'yay'Note:
this.$routeis only available inside components registered with Vue Router.
For modern Vue 3 projects using the Composition API, you can use the useRoute() composable:
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.query.test) // outputs 'yay'To handle cases where a query parameter might be missing, check for undefined or provide a fallback:
const value = this.$route.query.test || 'default'
// or for Composition API:
// const value = route.query.test || 'default'Query parameters
Query parameters are added at the end of the URL with a question mark (?) which is itself followed by the key-value pairs. Query parameters are URL extensions used to define specific content or actions which are based on the data that are being passed.