Usually, developers (including myself :D) use ref(), reactive() or even computed() to store state that could be easily be handled by the URL query or params.
In this article, I would like to show you how you can utilize this powerful browser native functionality in your Vue app 🚀
Code
To use query params in your Vue application, the easy way, you can use Vue Router's push method:
<script lang="ts" setup>
import { useRouter } from 'vue-router';
const { push } = useRouter();
</script>
This router method can be later used in your application after some event (like button click) to save the state to URL query param:
const saveUserNameToQuery = (name: string) => {
push({
query: {
username: name,
},
});
}
To change only certain query param while maintaining the rest in the same state use this:
const { currentRoute, push } = useRouter();
const updateQueryState = (parameter: string, value: string) => {
push({
query: {
...currentRoute.value.query,
[parameter]: value,
},
});
}
To reset a query params after some condition, you can use the following approach:
const resetQuery = () => {
push({
query: {},
});
}
There is much more things you can do with Vue Router but this one I wanted to show as I was recently using it to develop a new feature, and a completely new project. https://router.vuejs.org/
Summary
And this is it! You have successfully managed to learn how to use Vue Router to easily modify the URL state and update the query params. This is a really useful feature that I am using on the daily basis and strongly recommend you to try :)
Comments