Inspired by the post by Lee Robinson about using URL to store state in React / Next.js applications (that you can check out https://x.com/leeerob/status/1708280997488333078?s=20) I decided to write this article where I am going to show you how to persist state by using URL.
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.
Source: https://d186loudes4jlv.cloudfront.net/http/images/query_string_components.png
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.
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 :)