DEV Community

Cover image for Using URL to store state in Vue
Jakub Andrzejewski
Jakub Andrzejewski

Posted on

Using URL to store state in Vue

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.

URL query 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>


Enter fullscreen mode Exit fullscreen mode

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,
    },
  });
}


Enter fullscreen mode Exit fullscreen mode

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,
    },
  });
}


Enter fullscreen mode Exit fullscreen mode

To reset a query params after some condition, you can use the following approach:



const resetQuery = () => {
  push({
    query: {},
  });
}


Enter fullscreen mode Exit fullscreen mode

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 :)

Top comments (8)

Collapse
 
seven profile image
Caleb O.

Unrelated. But, for React folks who might stumble upon this and wonder — "is this is even possible in React?"

Yes, it is. You can read about this mental model here: meje.dev/blog/keep-state-in-the-url

Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

It is related as it is the same functionality but just in a different framework. Thanks for sharing!

Collapse
 
seven profile image
Caleb O.

The pleasure is mine

Collapse
 
hafizjavaidi profile image
Hafiz Javaid Iqbal

Hi,
Can you please tell how we can handle this using typescript when we try to get particular query param because according to my understanding typescript don't know the type and properties of query.

Pardon me if question is not clear

Thanks

Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

Hey,

Don't be affraid to ask questions :)

So the way how Vue Router works is that it has a TS support so any query or param will have a same type which will be either string or string[] because this is what eventually these values are -> strings. So if you want to keep there some numbers or objects, you have to remember to parse it to appriopriate types.

This union type of string | string[] can be tricky sometimes because if you have a function that accepts a string parameter and you will pass a currentRoute.value.query.myAwesomeQuery you will get a TS error as string is not compatibile with string | string []. So in some case you may need to cast the type like currentRoute.value.query.myAwesomeQuery as string

Collapse
 
asmyshlyaev177 profile image
Alex

Can store any complex object in query params, github.com/asmyshlyaev177/state-in... use encodeState and decodeState functions, decoded state will infer types and shape of data.

Collapse
 
hinogi profile image
Stefan Schneider

I think that this approach may get difficult. Let's say you have multiple tables that are sortable on one page.

Also, there is a character limit for urls :D

Collapse
 
jacobandrewsky profile image
Jakub Andrzejewski

Agree, for that, I would not recommend that. The idea is to use this instead of:

const category = ref('shoes')
Enter fullscreen mode Exit fullscreen mode