Query parameters are key-value pairs, which are added to the end of URLs after a question mark as in the following url.
http://example.com?category=sport
In this article, we will give some points to you should consider while working query parameters in your Vue 3 application. Let's get started with how to set a route including query parameters.
Setting Routes With Query Parameters
Link Routing
RouterLink component in vue accepts a string path in addition this you can also object including path and query parameters to navigate a user to a route. Here is an example of a link that will be navigate user to path "/about?category=sport":
<router-link :to="{ path: "/about", query: { category: "sport" } }">Sport</router-link>
<!-- http://example.com/about?category=sport -->
Routing Programmatically
The Vue router also provides some methods to handle navigation smoothly. One is the useRouter method, which includes the push method to programmatically redirect a user to another route.
import { useRouter } from "vue-router"
const router = useRouter();
router.push({ path: "/about", query: { category: "sport" } });
Getting Query Parameters In URL with Vue Router
The second thing you should know about query parameters is getting query parameters from a URL. You can accomplish this with useRoute method from the vue-router package as in the following example.
<template>
<!-- http://example.com/about?category=music -->
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script>
import { defineComponent } from "vue";
import { useRoute } from "vue-router";
export default defineComponent({
setup() {
const route = useRoute();
// Get the query param
console.log(route.query);
// {category:"music"}
},
});
</script>
Watching Changes in Query Parameters
You may fetch different data based on the query parameters from your API so, you would need to watch changes in URL query parameters. Here is an example using the watch method to fetch data from the jsonplaceholder fake API .
<template>
<div class="about">
<h1>This is an about page</h1>
{{data}}
</div>
</template>
<script>
import { defineComponent, watch, ref } from "vue";
import { useRoute } from "vue-router";
export default defineComponent({
setup() {
const data = ref([]);
const route = useRoute();
watch(
// Detect the changes in query params
() => route.query.category,
(newValue) => {
fetch("https://jsonplaceholder.typicode.com/" + newValue)
.then((response) => response.json())
.then((json) => (data.value = json));
},
{ immediate: true }
);
return {
data,
};
},
});
</script>
Conclusion
In this article we have covered how to handle Vue query params with vue-router by showing a few examples. But, these are a few examples of how to use query parameters in your vue app but, you can use query parameters more such as filtering state, showing search results, etc.
Thank you for reading