1. Demand background

After a successful login, the user information is returned and stored in vuex, and the home page is displayed. Because vuEX status is shared globally, you can obtain user information on the home page.

      Login({
        username: this.username,
        password: this.password,
      })
        .then((resp) = > {
          if (resp.successful) {
            this.$store.commit(SetUserInfo, resp.data);
            this.$router.push({
              name: "Home"
            });
          }
        })
        .catch((err) = > {
          this.$message.error(err.errorMesg);
        });
Copy the code

If only the login page has the logic to obtain user information throughout the project, and further, the logic to obtain user information depends on the login page, then when jumping to another route, the user information stored in vuEX on the refresh page will be lost.

2. Why does page refresh cause status loss

The reason a page refresh causes a loss of state is because the page refresh is equivalent to a VUE instance rebuild. Instance rebuild means that the state is restored to its initial state. However, the user information is obtained through the interface and does not exist in the initial state, so there will be state loss.

3. How do I resolve the status loss caused by refreshing

The solution to state loss due to refresh is a long way off. This blog combines sessionStorage and vuex to solve this problem.

3.1 Obtaining User Information Storage in sessionStorage

    [SetUserInfo](state, payload) {
      state.userInfo = payload;
      window.sessionStorage.setItem(UserInfoKey, JSON.stringify(payload));
    },
Copy the code

3.2 Recovering User Information from sessionStorage to VUex

export default function restoreUser(store) {
  const userInfo = window.sessionStorage.getItem(UserInfoKey);
  if (userInfo) {
    store.replaceState({
      userInfo: JSON.parse(userInfo) }); }}Copy the code

3.3 Using restoreUser logic as a VuEX plug-in

const store = new Vuex.Store({
  ...
  plugins: [
    restoreUser,
  ]
});
Copy the code

When the page is refreshed, the VUE instance is rebuilt and vuex is initialized. During initialization, user information is recovered from sessionStorage to Vuex. Therefore, user information exists in the initial vuEX state.

Complete the case

Case code

The resources

  • sessionStorage
  • vuex plugins