How to Get Query Params in Vue: Simple Guide
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' }.
export default { mounted() { console.log(this.$route.query); } }
Example
This example shows a Vue component that reads query parameters and displays them on the page. It updates reactively if the query changes.
<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>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.
/* 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.queryto react to changes. - Ensure Vue Router is installed and used.
Key Takeaways
this.$route.query inside Vue components to get query parameters.$route to be available.$route.query to react to query parameter changes dynamically.$route.query only inside Vue component context or via router instance.