0
0
VueHow-ToBeginner · 3 min read

How to Get Query Params in Vue: Simple Guide

In Vue, you can get query parameters using this.$route.query inside a component when using Vue Router. This object holds all query params as key-value pairs, accessible reactively.
📐

Syntax

Use this.$route.query inside your Vue component to access query parameters. It returns an object where each key is a query parameter name and the value is its string value.

For example, if the URL is /page?user=alice&id=123, then this.$route.query will be { user: 'alice', id: '123' }.

javascript
export default {
  mounted() {
    console.log(this.$route.query);
  }
}
Output
{ user: 'alice', id: '123' }
💻

Example

This example shows a Vue component that reads query parameters and displays them on the page. It updates reactively if the query changes.

vue
<template>
  <div>
    <h2>Query Parameters</h2>
    <ul>
      <li v-for="(value, key) in $route.query" :key="key">
        {{ key }}: {{ value }}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  watch: {
    '$route.query'(newQuery) {
      console.log('Query changed:', newQuery);
    }
  }
}
</script>
Output
Query Parameters user: alice id: 123
⚠️

Common Pitfalls

1. Not using Vue Router: Query params come from the router. Without Vue Router, this.$route is undefined.

2. Accessing query params outside component context: this.$route only works inside Vue components. For other files, import the router instance.

3. Query params are always strings: Even if numbers are passed, they come as strings. Convert them if needed.

javascript
/* Wrong: Trying to access query params without Vue Router */
console.log(this.$route.query); // Error: this.$route is undefined

/* Right: Inside a Vue component with Vue Router */
export default {
  mounted() {
    console.log(this.$route.query);
  }
}
📊

Quick Reference

  • this.$route.query: Access query params object inside Vue components.
  • Query params are strings; convert if needed.
  • Watch $route.query to react to changes.
  • Ensure Vue Router is installed and used.

Key Takeaways

Use this.$route.query inside Vue components to get query parameters.
Query parameters are strings; convert them if you need numbers or other types.
Vue Router must be installed and used for $route to be available.
Watch $route.query to react to query parameter changes dynamically.
Access $route.query only inside Vue component context or via router instance.