You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let lifeData = {};
try{
// 尝试获取本地是否存在lifeData变量第一次启动APP时是不存在的
lifeData = uni.getStorageSync('lifeData');
}catch(e){
}
// 需要永久存储且下次APP启动需要取出的在state中的变量名
let saveStateKeys = ['vuex_user', 'vuex_token', 'vuex_userInfo'];
// 保存变量到本地存储中
const saveLifeData = function(key, value){
// 判断变量名是否在需要存储的数组中
if(saveStateKeys.indexOf(key) != -1) {
// 获取本地存储的lifeData对象将变量添加到对象中
let tmp = uni.getStorageSync('lifeData');
// 第一次打开APP不存在lifeData变量故放一个{}空对象
tmp = tmp ? tmp : {};
tmp[key] = value;
// 执行这一步后所有需要存储的变量都挂载在本地的lifeData对象中
uni.setStorageSync('lifeData', tmp);
}
}
const store = new Vuex.Store({
state: {
// 如果上面从本地获取的lifeData对象下有对应的属性就赋值给state中对应的变量
// 加上vuex_前缀是防止变量名冲突也让人一目了然
vuex_user: lifeData.vuex_user ? lifeData.vuex_user : {username:'',password:''},
vuex_token: lifeData.vuex_token ? lifeData.vuex_token : '',
vuex_userInfo: lifeData.vuex_userInfo ? lifeData.vuex_userInfo : {}
// 如果vuex_version无需保存到本地永久存储无需lifeData.vuex_version方式
// vuex_version: '1.0.1',
// vuex_demo: '绛紫',
},
mutations: {
$uStore(state, payload) {
// 判断是否多层级调用state中为对象存在的情况诸如user.info.score = 1
let nameArr = payload.name.split('.');
let saveKey = '';
let len = nameArr.length;
if(len >= 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 {
// 单层级变量在state就是一个普通变量的情况
state[payload.name] = payload.value;
saveKey = payload.name;
}
// 保存变量到本地,见顶部函数定义
saveLifeData(saveKey, state[saveKey])
}
}
})
export default store