Storing User Interactions With 30 Lines of Code
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.
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.
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.
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.
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]).