index.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. Vue.use(Vuex)
  4. let lifeData = {};
  5. try {
  6. // 尝试获取本地是否存在lifeData变量,第一次启动APP时是不存在的
  7. lifeData = uni.getStorageSync('lifeData');
  8. } catch (e) {}
  9. // 需要永久存储,且下次APP启动需要取出的,在state中的变量名
  10. let saveStateKeys = ['userInfo', 'goods',
  11. 'isHaveService'
  12. ];
  13. // 保存变量到本地存储中
  14. const saveLifeData = function(key, value) {
  15. // 判断变量名是否在需要存储的数组中
  16. if (saveStateKeys.indexOf(key) != -1) {
  17. // 获取本地存储的lifeData对象,将变量添加到对象中
  18. let tmp = uni.getStorageSync('lifeData');
  19. // 第一次打开APP,不存在lifeData变量,故放一个{}空对象
  20. tmp = tmp ? tmp : {};
  21. // if(key == 'contractTip' && tmp[key] < value){
  22. // uni.vibrateLong({
  23. // success: function () {
  24. // console.log('震动成功');
  25. // }
  26. // });
  27. // }
  28. // if(key == 'taskTip' && tmp[key] < value){
  29. // uni.vibrateLong({
  30. // success: function () {
  31. // console.log('震动成功');
  32. // }
  33. // });
  34. // }
  35. tmp[key] = value;
  36. // 执行这一步后,所有需要存储的变量,都挂载在本地的lifeData对象中
  37. uni.setStorageSync('lifeData', tmp);
  38. }
  39. }
  40. const store = new Vuex.Store({
  41. modules: {},
  42. state: {
  43. sysinfo: uni.getSystemInfoSync(), //系统信息
  44. hasLogin: false,
  45. isHaveService: false,
  46. goods: []
  47. },
  48. mutations: {
  49. $uStore(state, payload) {
  50. // 判断是否多层级调用,state中为对象存在的情况,诸如user.info.score = 1
  51. let nameArr = payload.name.split('.');
  52. let saveKey = '';
  53. let len = nameArr.length;
  54. if (nameArr.length >= 2) {
  55. let obj = state[nameArr[0]];
  56. for (let i = 1; i < len - 1; i++) {
  57. obj = obj[nameArr[i]];
  58. }
  59. obj[nameArr[len - 1]] = payload.value;
  60. saveKey = nameArr[0];
  61. } else {
  62. // 单层级变量,在state就是一个普通变量的情况
  63. state[payload.name] = payload.value;
  64. saveKey = payload.name;
  65. }
  66. // 保存变量到本地,见顶部函数定义
  67. saveLifeData(saveKey, state[saveKey])
  68. },
  69. login(state, provider) {
  70. state.hasLogin = true;
  71. state.userInfo = provider;
  72. uni.setStorageSync('userInfo', provider)
  73. },
  74. logout(state) {
  75. state.hasLogin = false;
  76. state.userInfo = {};
  77. uni.removeStorageSync('userInfo')
  78. },
  79. goodCar(state, provider) {
  80. state.goods = provider;
  81. uni.setStorageSync('goods', provider)
  82. },
  83. goodService(state, provider) {
  84. state.isHaveService = provider;
  85. uni.setStorageSync('isHaveService', provider)
  86. },
  87. },
  88. actions: {
  89. },
  90. getters: {
  91. getUserInfo(state) {
  92. return state.userInfo
  93. }
  94. }
  95. })
  96. export default store