Explain Codes LogoExplain Codes Logo

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

javascript
vue-router
url-parameters
lifecycle-hooks
Alex KataevbyAlex Kataev·Dec 7, 2024
TLDR

In Vue.js, you can snatch query parameters from a URL in an instant using this.$route.query. Consider a URL like http://example.com/?user=alice, get the parameter this way:

// "Alice" decided to join the party const user = this.$route.query.user; // "alice"

The life of the party, Vue Router, injects the $route object into your app, enabling quick access to the treasure trove of query parameters.

Straight to the source - no middleman

If you're fond of DIY, you can directly delve into the built-in JavaScript API URLSearchParams:

// Who needs a library when you have built-in methods? const urlParams = new URLSearchParams(window.location.search); const paramName = urlParams.get('paramName'); // "parameter ninja"

Should you find yourself outside the Vue.js dojo, URLSearchParams requires no additional libraries and works straight out-of-the-box like magic.

Life and times of a Vue.js component

Vue.js components go through different stages in their lifetime. To access query parameters as soon as your component breathes its first breath, use Vue's created() lifecycle hook:

created() { // Cracking the secret code of query parameters console.log(this.$route.query); }

Ready to dive in once the DOM is fully loaded and settled? The mounted lifecycle hook comes to your rescue:

mounted() { // "I spy with my little eye something beginning with..." const specificParam = this.$route.query.paramName; console.log(specificParam); // Logging mission accomplished }

Custom routing

Does your app dream big? If dynamic routing is your thing, map query parameters to props and AMPLIFY your routing game:

// We're going on a road trip, and props are coming along! const router = new VueRouter({ routes: [ { path: '/search', component: SearchComponent, props: (route) => ({ query: route.query.q }) } ] }); // And at the SearchComponent side: props: ['query'],

Watch and learn

For the curious cat types, VueRouter allows you to watch for parameter changes, reacting in profound ways to the game of hide-and-seek between values:

watch: { // "I see you, Mr. Query Parameter. You can't hide from me!" '$route.query.paramName'(newValue, oldValue) { // Your action when the query parameter changes } }

Routing etiquette

Not fond of hash (#) in your URLs? Let VueRouter whisper sweet nothings to your URLs in the 'history' mode:

const router = new VueRouter({ mode: 'history', // Plus, your existing routes here... });

Broaden your routing horizons with navigation guards like beforeRouteUpdate for those pesky parameter transitions.

Default props

Set default values and keep your Vue props in check with type validations:

props: { paramName: { type: String, // "'default' is my middle name", said the humble paramName default: 'default' } }

Moving around in style

Make your way around the Vue.js world programmatically, passing query parameters like a VIP with this.$router.push:

// "Make way, 'Vue.js' coming through" this.$router.push({ path: '/search', query: { q: 'Vue.js' } });

Quirk alerts

Heads up! Some quirks you might want to prepare for:

  • URL restructuring: When you change URLs, make sure no parameter gets left behind.
  • Browser compatibility: Not every browser is a fan of URLSearchParams - consider polyfills.
  • URI decoding: Special characters and spaces in URL parameters are encoded. Decode when necessary.