state.ts 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /**
  2. *公共数据
  3. */
  4. import { initGlobalState } from 'qiankun';
  5. import { store } from '/@/store';
  6. import { router } from '/@/router';
  7. import { getToken } from '/@/utils/auth';
  8. let actions;
  9. //定义传入子应用的数据
  10. export function getProps() {
  11. return {
  12. data: {
  13. publicPath: '/',
  14. token: getToken(),
  15. store: store,
  16. router,
  17. isMounted: false,
  18. },
  19. };
  20. }
  21. /**
  22. * 定义全局状态,并返回通信方法,在主应用使用,微应用通过 props 获取通信方法。
  23. * @param state 主应用穿的公共数据
  24. */
  25. export function initGlState(
  26. info: any = { token: '', userInfo: {}, isMounted: false, locationObj: null, locationId: '', pageObj: null, widthScale: 1, heightScale: 1 }
  27. ) {
  28. if (actions) return;
  29. // 初始化state
  30. actions = initGlobalState(info);
  31. // 设置新的值
  32. actions.setGlobalState({
  33. token: getToken(),
  34. isMounted: false,
  35. pageObj: {},
  36. widthScale: 1,
  37. heightScale: 1,
  38. url: {},
  39. });
  40. // 注册 观察者 函数 - 响应 globalState 变化,在 globalState 发生改变时触发该 观察者 函数。
  41. actions.onGlobalStateChange((newState, prev) => {
  42. // state: 变更后的状态; prev 变更前的状态
  43. console.info('newState', newState);
  44. console.info('prev', prev);
  45. for (const key in newState) {
  46. console.info('onGlobalStateChange', key);
  47. }
  48. });
  49. }
  50. export function getActions() {
  51. if (!actions) initGlState();
  52. return actions;
  53. }