Vuex combines session storage data to solve the problem of data loss when refreshing the page

Vuex combines session storage data to solve the problem of data loss when refreshing the page

Preface

In the form filter items in the project, after selecting, the data will change when the page is refreshed, and it will not be retained on the option you selected.
Vuex is used to save data in the project, but after the webpage is refreshed, the data saved in the store is lost.

Tip: The following is the main content of this article. The following cases can be used for reference

1. Reasons:

Vuex is a global data state management mechanism. The data in the store is stored in the running memory. When the page is refreshed, the page will reload the Vue instance, and the data in the store will be reassigned to the initialized state.

2. Solution ideas:

Use vuex with local storage to refresh the page without losing data

1. Local storage method:

1. localStorage: Permanent storage. The data stored in localStorage will not disappear after closing the page or browser. Unless you actively delete the data, it will never disappear.
Taking Chrome browser as an example, the data is placed in C:\Users\your computer name\AppData\Local\Google\Chrome\User Data\Default\Local Storage\leveldb
2. sessionStorage: It is only valid in the current session. The data will be destroyed when the current page or browser is closed. SessionStorage is data that always exists in the window of the same origin. It is still there when the page is refreshed, and it is destroyed as long as the current page is closed.
3. Cookie: If you do not set an expiration date in the browser, the cookie is saved in the memory and its life cycle ends when the browser is closed. This type of cookie is referred to as a session cookie. If the expiration time of the cookie is set in the browser, the cookie is saved on the hard disk. After closing the browser, the cookie data still exists until the expiration time expires. . The size of the data stored in cookies is about 4kb, generally no more than 20, and cannot store large data.

Extension: Cookie application scenarios (1) Determine whether the user has logged in to the website so that the user can log in automatically (or remember the password) the next time. If we delete cookies, you must fill in the login information again every time you log in.
(2) Save information such as the time of last login.
(3) Save the last viewed page (save the visited route information)
(4) Browser behavior tracking (such as tracking and analyzing user behavior, etc.)
(5) Personalized settings (such as user-defined settings, themes, etc.)

2. Implementation steps:

Since vue is a single-page application, all operations are completed on one page, and this project is only used in the currently opened project, so it is more appropriate to use sessionStorage

  • The data is saved in the state. The state data is modified through the mutation method. When the mutation modifies the state, the data is also saved in the sessionStorage.
  • When the project is opened, initialize the data in App.vue. If there is data stored locally, call the method in actions to assign values ​​to the state.
  • When a form item is selected, the data in the state is modified at the same time.
//store/selectData.js
const state = {//data stored in state dataList: {
    exchangeIdSum: null,
  }
}
const mutations = {
  setExchangeIdSum(state, data) { //Reassign the selected data and save it to sessionStorage state.dataList.exchangeIdSum = data
    sessionStorage.setItem('dataList',JSON.stringify(state.dataList))
  }
  setDataList(state, data) {
    state.dataList = JSON.parse(JSON.stringify(data))
  }
}
const actions = {
  resetDataList: ({commit}, list) => {
    setTimeout(() => {
      commit('setDataList', list)
    }, 2000);
  }
}
export default {
  state,
  mutations,
  actions,
}

//Operation methods in the form filtering page: {
  exchangeChange(val) {//Modify the data in state when the drop-down box is selected this.$store.commit('selectData/setExchangeIdSum', val)
  },
}
//App.vue in create(){//As soon as the page is entered, determine whether there is data in sessionStorage sessionStorage.getItem('dataList')?
  this.$store.dispatch('selectData/resetDataList', JSON.parse(sessionStorage.getItem('dataList'))):{}
}

3. Optimization:

Because when modifying state data before, each mutation must modify sessionStorage, but if there is a lot of state data to be modified, sessionStorage will be modified every time, which is a bit troublesome.

insert image description here

solve:
① You can store data directly in sessionStorage ② The page will be lost every time Vue is refreshed. You can store data in sessionStorage before refreshing the page. The beforeunload event can be triggered before refreshing the page

This concludes this article about how to use vuex combined with session storage data to solve the problem of data loss when refreshing a page. For more relevant vuex session storage data content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to monitor changes in localStorage or sessionStorage in a Vue project
  • Different background session operations caused by Vue using axios
  • Example of implementing session and token login status verification using vue+koa2
  • Use sessionStorage to remember password function in vue
  • Detailed explanation of the use of localstorage and sessionstorage in Vue

<<:  Use Nginx to build a streaming media server to realize live broadcast function

>>:  A brief introduction to MySQL storage engine

Recommend

JavaScript implements a box that follows the mouse movement

This article shares the specific code of JavaScri...

Web front-end performance optimization

Web front-end optimization best practices: conten...

Simple implementation method of vue3 source code analysis

Table of contents Preface 🍹Preparation 🍲vue3 usag...

Deployment and Chinese translation of the docker visualization tool Portainer

#docker search #docker pull portainer 1. Download...

Vite introduces the implementation of virtual files

Table of contents background Importing virtual fi...

Solve the problem that Docker cannot ping the host machine under Mac

Solution Abandon the Linux virtual machine that c...

How to use Docker to package and deploy images locally

First time using docker to package and deploy ima...

How many ports can a Linux server open at most?

Table of contents Port-related concepts: Relation...

A brief analysis of adding listener events when value changes in html input

The effect to be achieved In many cases, we will ...

Example of how to configure multiple virtual hosts in nginx

It is very convenient to configure virtual host v...

A brief discussion on macrotasks and microtasks in js

Table of contents 1. About JavaScript 2. JavaScri...

Html Select uses the selected attribute to set the default selection

Adding the attribute selected = "selected&quo...

CentOS7 firewall and port related commands introduction

Table of contents 1. Check the current status of ...

How to install the latest version of docker using deepin apt command

Step 1: Add Ubuntu source Switch to root su root ...

Illustration-style website homepage design New trend in website design

You can see that their visual effects are very bea...