state.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. defaultTheme: 'blue',
  19. },
  20. actions: getActions(),
  21. };
  22. }
  23. /**
  24. * 定义全局状态,并返回通信方法,在主应用使用,微应用通过 props 获取通信方法。
  25. * @param state 主应用穿的公共数据
  26. */
  27. export function initGlState(
  28. info: any = {
  29. token: '',
  30. userInfo: {},
  31. isMounted: false,
  32. locationObj: null,
  33. locationId: '',
  34. pageObj: null,
  35. widthScale: 1,
  36. heightScale: 1,
  37. dataPickerHoverEnabled: true,
  38. }
  39. ) {
  40. if (actions) return;
  41. // 初始化state
  42. actions = initGlobalState(info);
  43. // 设置新的值
  44. actions.setGlobalState({
  45. token: getToken(),
  46. isMounted: false,
  47. pageObj: {},
  48. widthScale: 1,
  49. heightScale: 1,
  50. url: {},
  51. dataPickerHoverEnabled: localStorage.getItem('dataPickerHoverEnabled') !== 'false',
  52. });
  53. // 注册 观察者 函数 - 响应 globalState 变化,在 globalState 发生改变时触发该 观察者 函数。
  54. actions.onGlobalStateChange((newState, prev) => {
  55. // state: 变更后的状态; prev 变更前的状态
  56. console.info('newState', newState);
  57. console.info('prev', prev);
  58. for (const key in newState) {
  59. console.info('onGlobalStateChange', key);
  60. }
  61. });
  62. }
  63. export function getActions() {
  64. if (!actions) initGlState();
  65. return actions;
  66. }