Vuex data persistence in uniapp

question

The data stored in Vuex in the H5 application is lost after refreshing the page.

reason

The data in the store of Vuex is stored in the running memory. When the page is refreshed, the Vue instance will be reloaded on the page, and the Vuex data will be reinitialized, resulting in the loss of data in Vuex when the page is refreshed.

Solution

Use the vuex-persistedstate plugin

1. Execute in the project directory: npm install --save vuex-persistedstate;
2. Modify store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import persistedState from "vuex-persistedstate"

Vue.use(Vuex)

const store = new Vuex.Store({
    
    
	plugins: [
		persistedState({
    
    
			storage: {
    
    
				getItem: key => uni.getStorageSync(key),
				setItem: (key, value) => uni.setStorageSync(key, value),
				removeItem: key => uni.removeStorageSync(key)
			}
		})
	],
	state:{
    
    //存放状态
        "username":'',
        "userid":''
    },
	mutations:{
    
    
		//...
	},
	actions:{
    
    
		//...
	},
	//...
})

export default store

After use, open the browser and use console debugging to see that the data is stored in window.localStorage.vuex , which is actually the same as the stored data location
provided by calling uniapp . Official document link: https://uniapp.dcloud.io/api/ 数据缓存APIstorage/storage.html

Note: In the APP-PLUS environment, this data will not be cleared (or initialized) by default when the application exits.

Guess you like

Origin blog.csdn.net/Mr_Bobcp/article/details/125876232