Storing User Interactions With 30 Lines of Code

Brenton Klik
2 min readOct 17, 2022

--

A user’s interactions are frequently stored in the query section of a site’s URL. These interactions could be searches, pagination changes, filters, etc. It allows state to survive reload, be quickly shared with others, and recalled from browser history. In route-based navigation with Vue Router, these query results are easily lost as the user navigates from one path to the next. In this article, we’ll examine one way of making these queries persist during a session.

Examining Default Behavior

Let’s start by looking at the out-of-the-box behavior of the Vue Router for a simple application with three paths.

Simple three path Route Record

In the following animation, I will navigate between these paths using the Tab links and add some query data to the route as I go. Using the browser back button, I can recall the full path with queries. However, when I use Tabs links, the query data is lost.

Default route behavior has poor query retention

Adding Query Storage and Recall

It would be a much better experience, if query strings where saved and restored as the user navigated between paths. One way in which we can achieve this is with a Map, and the Router.beforeEach() method.

Injecting stored queries in the path

As shown in the following animation, the route/query behavior is much improved. Now each path’s queries are retained, and the URL is returned to the last known state using in app navigation or browser controls.

Route experience is much improved

When you want to clear the queries on a route, you simply push an empty ‘params’ Array to the route query.

Conclusion

The tweaked router behavior makes query data for each path easier to work with and predictable. User interactions can be stored to the URL without risk of them being lost as the user navigates around the application.

The implementation above isn’t perfect. For instance, if a sub route is used, the query would not carry forward. However, the code can be easily tweaked for this use case (hint: query.split(‘/’)[1]).

--

--

Brenton Klik
Brenton Klik

Written by Brenton Klik

Brenton Klik is an Interaction Designer in the Washington DC area. He designs interfaces and experiences for web, mobile, and desktop platforms.