Accessing URL query parameters is a common need in Vue 3 applications, whether for filters, search, or dynamic data. With the Composition API and Vue Router, it’s simple and reliable.
This quick guide shows you how to read query parameters inside a Vue 3 component, react to changes, and handle edge cases.
Accessing Query Parameters with useRoute()
First, make sure you have vue-router installed (npm install vue-router@4 or yarn add vue-router@4) and set up in your Vue project.
The useRoute() function gives you access to the current route object, which holds all the details about the page you're on, including query parameters in its .query property.
Basic Examples
Let's assume your URL looks like: http://your-app.com/products?category=electronics&page=2
Get All Query Parameters
Access route.query directly to get an object containing all parameters.
<template> <div> <p>All Query Params: {{ route.query }}</p>
</div>
</template>
<script setup>
import { useRoute } from 'vue-router'; // Required for useRoute()
const route = useRoute(); // Get the current route object
// console.log(route.query); // In script, access like this
</script>
Get a Specific Query Parameter
Access parameters by their name, like route.query.parameterName.
<template> <div>
<p>Category: {{ route.query.category }}</p>
<p>Page: {{ route.query.page }}</p>
</div>
</template>
<script setup>
import { useRoute } from 'vue-router';
const route = useRoute();
// console.log(route.query.category); // 'electronics'
// console.log(route.query.page); // '2' (as a string)
</script>
Also Read: Why Choose Vue.js: Key Benefits for Developers and Businesses
React to Query Parameter Changes
The route.query object is reactive. Any changes in the URL's query will automatically update route.query and trigger reactivity in your template or computed properties. If you need to run custom code when parameters change, use watch.
<template> <div>
<p>Watching Category: {{ route.query.category }}</p>
</div>
</template>
<script setup>
import { useRoute } from 'vue-router';
import { watch } from 'vue'; // Needed for watch()
const route = useRoute();
// This code runs whenever route.query.category changes
watch(() => route.query.category, (newCategory, oldCategory) => {
console.log(`Category changed from '${oldCategory}' to '${newCategory}'`);
// You might refetch data here based on newCategory
});
</script>
When to Use URL Query Parameters
Use query parameters for information that:
- Filters or sorts data: products?color=red&sort=price
- Indicates pagination: articles?page=3
- Contains search terms: search?q=vue+tutorial
- Is optional for the page to function: settings?theme=dark
Key Takeaway
To get URL query parameters in Vue 3, simply use useRoute() from vue-router and access the route.query object. This object provides reactive access to all parameters, allowing you to easily retrieve them, set defaults, and respond to URL changes in your components.
Related Resources