user.ts 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import { loginPassword } from '/@/api';
  2. import { useCookies } from '@vueuse/integrations/useCookies';
  3. import { defineStore } from 'pinia';
  4. import { wxLogin } from '/@/api'
  5. const { VITE_TOKEN_KEY } = import.meta.env;
  6. const token = useCookies().get(VITE_TOKEN_KEY as string);
  7. interface StoreUser {
  8. token: string;
  9. wxOpenId: string;
  10. info: Record<any, any>;
  11. }
  12. export const useUserStore = defineStore({
  13. id: 'user',
  14. state: (): StoreUser => ({
  15. token: token,
  16. wxOpenId:'o3S0L1Hyd3O0vYI2Kr1lFDEtEO2k',
  17. info: {
  18. name:'test',
  19. wxOpenId:'test1',
  20. },
  21. }),
  22. getters: {
  23. getUserInfo(): any {
  24. return this.info || {};
  25. },
  26. getWxOpenId(): any {
  27. return this.wxOpenId || useCookies().get('wxOpenId');
  28. },
  29. },
  30. actions: {
  31. setInfo(info: any) {
  32. this.info = info ? info : '';
  33. },
  34. setWxOpenId(code: string){
  35. wxLogin(code).then(res => {
  36. console.log('wxlogin',res)
  37. let { openid } = res.data
  38. this.wxOpenId = openid ? openid : '';
  39. if(openid){
  40. useCookies().set('wxOpenId', openid)
  41. }
  42. })
  43. },
  44. login() {
  45. return new Promise((resolve) => {
  46. const { execute } = loginPassword();
  47. execute().then((res) => {
  48. // this.setInfo(res);
  49. resolve(res);
  50. });
  51. });
  52. },
  53. },
  54. persist: {
  55. key: 'token',
  56. storage: localStorage,
  57. paths: ['token'],
  58. },
  59. });