uni-app use vuex + vuex-persistedstate

Vuex is a state management tool based on vuex.js, which can be understood as a warehouse. Stored in it is the public state that can be reused by each component. In order to prevent the problem of refresh loss, we use the vuex-persistedstate plugin to do local persistent storage——

uni-app has built-in vuex, so we only need to install

npm install --save vuex-persistedstate

Create a new store directory, create a new store.js, the code is as follows

// <!-- 页面路径:store/index.js -->
import Vue from 'vue'
import Vuex from 'vuex'

//数据持久化插件
import createPersistedState from 'vuex-persistedstate'  


Vue.use(Vuex);//vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
    
    
    state:{
    
    //存放状态
        "username":"",
        "token":''
    },
	mutations:{
    
    
		updateToken(state,str){
    
    
			state.token=str
		}
	},
	actions:{
    
    
		
	},
	modules:{
    
    
		
	},
	plugins: [  
	    // 可以有多个持久化实例  
	    createPersistedState({
    
      
	      key: 'app_config_data',  // 状态保存到本地的 key   
	      paths: ['token', 'username'],  // 要持久化的状态,在state里面取,如果有嵌套,可以  a.b.c   
	      storage: {
    
      // 存储方式定义  
	        getItem: (key) => uni.getStorageSync(key), // 获取  
	        setItem: (key, value) => uni.setStorageSync(key, value), // 存储  
	        removeItem: (key) => uni.removeStorageSync(key) // 删除  
	      }  
	    })  
	  ]  
})
export default store

Inject store in main.js and modify the code as follows

//引入vuex
import store from './store/store.js'

Vue.prototype.$store = store

const app = new Vue({
    
    
    ...App,store
})
app.$mount()

It is currently in normal use, localized and can be stored persistently... If it is not compatible with other terminals, you can try to install mp-storage in the uni-app plug-in marketmp-storage

Guess you like

Origin blog.csdn.net/weixin_51198863/article/details/113918181