index.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import Vue from 'vue'
  2. import Vuex from 'vuex'
  3. import {apiWXLogin,apiLoginOut} from '@/api/user.js'
  4. import uniAsync from '@/utils/uni-async.js'
  5. Vue.use(Vuex);//vue的插件机制
  6. const token=uni.getStorageSync('token')||''
  7. let userInfo={}
  8. if(uni.getStorageSync('userInfo')){
  9. userInfo=JSON.parse(uni.getStorageSync('userInfo'))
  10. }
  11. //Vuex.Store 构造器选项
  12. const store = new Vuex.Store({
  13. state:{//存放状态
  14. token:token,
  15. userInfo:userInfo,
  16. },
  17. mutations:{
  18. // 添加token
  19. addToken(state,data){
  20. state.token=data
  21. uni.setStorageSync('token',data)
  22. },
  23. // 添加用户信息
  24. addUserData(state,data){
  25. state.userInfo=data
  26. uni.setStorageSync('userInfo',JSON.stringify(data))
  27. },
  28. // 清空用户信息和token
  29. removeUser(state){
  30. state.token='',
  31. state.userInfo={}
  32. uni.reLaunch({
  33. url:'/pages/login/login'
  34. })
  35. }
  36. },
  37. actions:{
  38. // 微信登录
  39. async WXLogin(context){
  40. let wxLoginRes=await uniAsync.login({
  41. provider:'weixin'
  42. })
  43. const res=await apiWXLogin({Code:wxLoginRes.code})
  44. if(res.code===200){
  45. context.commit('addToken',res.data.Authorization)
  46. context.commit('addUserData',res.data.UserInfo)
  47. }
  48. },
  49. // 退出登录
  50. async loginOut(context){
  51. const res=await apiLoginOut()
  52. if(res.code===200){
  53. uni.clearStorageSync()
  54. context.commit('removeUser')
  55. }
  56. }
  57. }
  58. })
  59. export default store