Use sessionStorage to fix page blank issue of F5 refresh due to vue route push params loss

2020年08月12日 2033Browse 0Like 0Comments

I experienced the issue(mentioned in the article title) when using the push method of Vue router to redirect to a new URL when clicking on some anchors today.

Usually, there are two typical ways to go to the new page(route) via using push method:

// way 1: named route
router.push({ name: 'user', params: { userId: '123' } })

// way 2: with query, resulting in /register?plan=private
router.push({ path: 'register', query: { plan: 'private' } })

The params passed by the first way(use params)will not be shown in the URL, so if we want to hide more details of the page, it's a better way. However, when I use this way, the web page turns out to be blank when I press F5 to update, as the page cannot get the route parameters which are used as data request params. The route params won't be persistant via this way, they will not exist when page reloads. This is becuase the named route is not pushed into history records, the browser is not able to find a record to reload.

Ways to fix

To fix this, we can use the second way(use query) to push route params and the parameters will persit even if a F5 update happens. However, the parameters will show up in the URL, and object parameters with several level-depth will turn into long garbled code. I don't want this as I hope to keep the URL address clean.

How about the other ways to fix this? I tried to create another state in the Vuex store to keep the data, but this doesn't work as well unless I use the plugin vuex-persistedstate. I checked its github repo and find it uses localStorage, sessionStorage or cookie to persist data. so why not use one of this web API directly instead of intalling another npm package? As I don't store much data.


The picture above is from stackoverflow.

I choose sessionStorage as my website is a SPA, persisting data in a session-wide is enough. And the API is also very easy to pick up.

export default {
	setPageData: (key, dataObj) => {
		let artist = JSON.stringify(dataObj);
		sessionStorage.setItem(key, [artist]);
	},

	getPageData: (key) => {
		return JSON.parse(sessionStorage.getItem(key));
	},
};

Reference

Sunflower

Stay hungry stay foolish

Comments