web123456

Uniapp uses vuex global variable wrapped by uview, required files

  • import Vue from 'vue'
  • import Vuex from 'vuex'
  • Vue.use(Vuex)
  • let lifeData = {};
  • try{
  • // Try to get whether the lifeData variable exists locally, it does not exist when the APP is launched for the first time
  • lifeData = uni.getStorageSync('lifeData');
  • }catch(e){
  • }
  • // The variable name in the state that needs to be retrieved after the APP is started next time. Those not in this list will not be stored permanently
  • let saveStateKeys = ['vuex_user', 'vuex_token'];
  • // Define a method saveLifeData to save variables to local storage
  • const saveLifeData = function(key, value){
  • // Determine whether the variable name key is in the array that needs to be stored. It's the one above, if there is one, store it
  • if(saveStateKeys.indexOf(key) != -1) {
  • // Get the locally stored lifeData object and add variables to the object
  • let tmp = uni.getStorageSync('lifeData');
  • // The first time I opened the APP, there is no lifeData variable, so I put an empty object in {}
  • tmp = tmp ? tmp : {};
  • tmp[key] = value;
  • // After performing this step, all variables that need to be stored are mounted in the local lifeData object
  • uni.setStorageSync('lifeData', tmp);
  • }
  • }
  • const store = new Vuex.Store({
  • //The following values ​​are only examples, please delete them during use
  • state: {
  • // If there is a corresponding property under the lifeData object obtained from the local area above, it will be assigned to the corresponding variable in the state
  • // Adding the vuex_ prefix to prevent variable name conflicts and makes people clear at a glance
  • vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {name: 'Bright Moon'},
  • vuex_token: lifeData.vuex_token ? lifeData.vuex_token : '',
  • // If vuex_version does not need to be saved to local permanent storage, there is no need for lifeData.vuex_version method
  • vuex_version: '1.0.1',
  • },
  • mutations: {
  • $uStore(state, payload) {
  • // Determine whether a multi-level call is called, and the state is an object exists, such as = 1
  • let nameArr = payload.name.split('.');
  • let saveKey = '';
  • let len = nameArr.length;
  • if(nameArr.length >= 2) {
  • let obj = state[nameArr[0]];
  • for(let i = 1; i < len - 1; i ++) {
  • obj = obj[nameArr[i]];
  • }
  • obj[nameArr[len - 1]] = payload.value;
  • saveKey = nameArr[0];
  • } else {
  • // Single-level variables are a normal variable in state
  • state[payload.name] = payload.value;
  • saveKey = payload.name;
  • }
  • // Save the variable saveKey to local, see the function definition at the top
  • saveLifeData(saveKey, state[saveKey])
  • }
  • }
  • })
  • export default store