1. Problem Description:

After a successful login, user information and menu information need to be stored in vuEX as global shared data. However, when the page is refreshed, the data in vuex will be reinitialized, resulting in data loss. Because the data in VUex is stored in running memory, when the page is refreshed, the page reloads the VUE instance and the data in VUex is reassigned.

2. Solution:

Method 1: Save vuEX data directly to browser cache (sessionStorage, localStorage, cookie)

Method 2: Request remote data again when the page is refreshed so that vuEX data can be dynamically updated

Method 3: Request remote data from the background in the parent page, and save vuex data to sessionStorage before page refresh (in case the returned data cannot be obtained when the page is loaded with too much request data)

Analysis:

The disadvantage of method 1 is that it is not safe and not suitable for storage of large amount of data.

Method two applies to a small amount of data, and does not appear network delay;

Method three is the key to speak, method two and method one use together.

3. Solution process: @1

3.1. Select the appropriate browser for storage

LocalStorage – is permanently stored locally unless you delete it;

SessionStorage – is stored until the current page is closed, not associated with other TAB pages;

Cookie – the cookie is stored according to the valid time you set, but the disadvantage is that it cannot store big data and is not easy to read, and will interact with the background.

** “sessionStorage” ** is selected in this method. The reason is that vue is a single page application, and all operations are routed in one page. Another reason is that sessionStorage can ensure that the data of sessionStorage is empty when the page is opened. LocalStorage reads the data from the last page opened.

3.2 solutions

Because the data in state is responsive, the sessionStorage also changes, and the value in state can only be changed through ** “mutations” **.

First, after the user logs in successfully, the user information and menu information are distributed and saved to VUEX through actions. Then the menu data of state in VUEX is calculated in the menu page, the data is parsed and assembled into the format required by the front-end component, and then the component is rendered to generate the menu tree. If the page is not refreshed, everything is fine.

“Synchronize user and menu data to VUEX after successful login”

“Listen for menu data in VUEX on menu page”

Page refresh solution:

When the page is refreshed, background data is asynchronously requested, and data in VUEX is dynamically updated. In this situation, network delay and large data volume may occur. At this point, the page is loaded before Vuex gets the data returned from the background, causing data loss. Therefore, the solution is to listen to the events before browser refresh and save the data in VUex to sessionStorage before browser refresh. After the refresh, if the data in asynchronous request is not returned, the data in sessionStorage will be directly obtained; otherwise, the data in VUex will be obtained. SessionStorage is used to fetch data from sessionStorage. Ensure data security, even access to sessionStorage data is safe, because every refresh will be reassigned, do not worry about data tampering problem, secondly, sessionStorage data encryption operation)

“Request data from background in parent page and listen for events before browser refresh, save vuex data to sessionStorage”

“Request data from the background on the parent page and distribute the returned data to VUEX”

3. Solution: @2 Vuex-PersistedState

Principle:

Store vuex state in localStorage or sessionStorage or cookie

When the page is refreshed, vuex data disappears, and vuex retrieves data from sessionStorage. In this way, data refresh is not lost

Usage:

Install: NPM install Vuex-PersistedState –save

In index.js under store, import and configure

import createPersistedState from "vuex-persistedstate"

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})
Copy the code

At this time can choose the location of the data storage, can be localStorage sessionStorage/cookie, here in storage to the sessionStorage, for example, the configuration is as follows:

import createPersistedState from "vuex-persistedstate"
const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState({
      storage: window.sessionStorage
  })]
})
Copy the code

Store specified state:

Vuex-persistedstate Enables all states to be persisted by default. The configuration is as follows:

import createPersistedState from "vuex-persistedstate" const store = new Vuex.Store({ // ... Plugins: [createPersistedState({storage: window.sessionStorage, reducer(val) {return { val.user } } })]Copy the code

Val corresponds to the store/modules folder in the js file, that is, stor/index import modules, can be printed to see. For which part of the data you want to store persistently, you can set the name of the data here. For now, I only want to store the data of user module persistently.

Note: If you want to configure multiple options at this point, write the plugins as a one-dimensional array, otherwise an error will be reported.

Import createPersistedState from "vuex-PersistedState" import createLogger from 'vuex/dist/ Logger '// Determine the environment Vuex indicates that the production environment does not use const debug = process.env.node_env! == 'production' const createPersisted = createPersistedState({ storage: window.sessionStorage }) export default new Vuex.Store({ // ... plugins: debug ? [createLogger(), createPersisted] : [createPersisted] })Copy the code

3, solution process: @3 vuex-along

Save a copy of state data to localStorage (localStorage, sessionStorage, cookie)

//App.vue

If (sessionStorage.getitem ("store")) {if (sessionStorage.getitem ("store")) { this.$store.replaceState(Object.assign({}, Parse (sessionStorage.getitem ("store"))))} // Save vuex information to sessionStorage when the page is refreshed window.addEventListener("beforeunload",()=>{ sessionStorage.setItem("store",JSON.stringify(this.$store.state)) }) } } </script>Copy the code

2. Use a third party plug-in like vuex-along (essentially caching it locally using sessions, etc.)

import Vue from 'vue' import Vuex from 'vuex' import VueXAlong from 'vuex-along' Vue.use(Vuex) let productData = require('@/assets/api/list.json') const moduleA = { state: { a1: 'a1', a2: Pay attention to vuex. Store({state: {productList: [],// cart data: [],// cart data}, mutations: SetProductList (state, data){state. ProductList = data}, // Add cart to cart id){ let cartIndex = state.cartList.findIndex(item => item.id === id) if(cartIndex < 0){ state.cartList.push({id, count: CartList [cartIndex].count++}}else{cartList[cartIndex].count++}}, id){ let cartIndex = state.cartList.findIndex(item => item.id === id) state.cartList.splice(cartIndex, 1) }, // Edit cart quantity editCartList(state, data){ let cartIndex = state.cartList.findIndex(item => item.id === data.id) state.cartList[cartIndex].count = data.count }, clearCart(state){ state.cartList = [] }, }, actions: {contextproductList (context){contextproductList (context){contextproductList (context){contextproductList (context){contextproductList (context){contextproductList (context){contextproductList (context); ProductData)}, 2000)}, buy(context){// Simulate an Ajax request by returning a promise object to the place where the action is committed. Reject)=>{setTimeout(()=>{context.com MIT ('clearCart') resolve({MSG :' reject ', code: 200}) //reject({message: 'Submit failed ', code: 300})}, 1000)})}}, modules: {ma: moduleA}, // Cache state data to storage plugins: [VueXAlong()], // Full parameter configuration (sessionStorage data recovery priority is higher than localStorage) /* plugins: [VueXAlong ({/ / set to save the collection name, avoid conflict with multiple projects under the site data name: 'my - app - VueXAlong', / / filter ma data to other data stored in localStorage local: {list: {list: ['ma.a1'], isFilter: {list: ['ma.a1'], isFilter: {list: ['ma.a1'], False,}, // Only use sessionStorage //justSession: true,})] */})Copy the code