index.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. Vue.use(Vuex)
  4. const store = new Vuex.Store({
  5. state: {
  6. token: '',
  7. userId: '',
  8. role: 'parent', // 用户的实际角色(数据库中的角色)
  9. currentRole: 'parent', // 当前视图模式(用于切换查看家长/孩子界面)
  10. familyId: '',
  11. nickname: '',
  12. currentChildId: '',
  13. children: []
  14. },
  15. mutations: {
  16. setToken(state, token) {
  17. state.token = token
  18. uni.setStorageSync('token', token)
  19. },
  20. setUserInfo(state, userInfo) {
  21. state.userId = userInfo.userId
  22. state.role = userInfo.role
  23. state.currentRole = userInfo.role // 初始化当前角色为实际角色
  24. state.familyId = userInfo.familyId
  25. state.nickname = userInfo.nickname
  26. // 保存到本地存储
  27. uni.setStorageSync('userId', userInfo.userId)
  28. uni.setStorageSync('role', userInfo.role)
  29. uni.setStorageSync('currentRole', userInfo.role)
  30. uni.setStorageSync('familyId', userInfo.familyId)
  31. },
  32. setChildren(state, children) {
  33. state.children = children
  34. if (children.length > 0 && !state.currentChildId) {
  35. state.currentChildId = children[0].id
  36. }
  37. },
  38. setCurrentChild(state, childId) {
  39. state.currentChildId = childId
  40. uni.setStorageSync('currentChildId', childId)
  41. },
  42. // 切换视图模式(不修改数据库中的实际角色)
  43. switchViewMode(state, role) {
  44. state.currentRole = role
  45. uni.setStorageSync('currentRole', role)
  46. },
  47. // 兼容旧的方法名
  48. switchRole(state, role) {
  49. state.currentRole = role
  50. uni.setStorageSync('currentRole', role)
  51. },
  52. logout(state) {
  53. state.token = ''
  54. state.userId = ''
  55. state.role = 'parent'
  56. state.currentRole = 'parent'
  57. state.familyId = ''
  58. state.nickname = ''
  59. state.currentChildId = ''
  60. state.children = []
  61. uni.removeStorageSync('token')
  62. uni.removeStorageSync('currentRole')
  63. }
  64. },
  65. actions: {
  66. login({ commit }, userInfo) {
  67. commit('setToken', userInfo.token)
  68. commit('setUserInfo', userInfo)
  69. },
  70. updateChildren({ commit }, children) {
  71. commit('setChildren', children)
  72. }
  73. }
  74. })
  75. export default store