• 前端微服务qiankun 2.x主子应用通信代码片段


    主应用代码

    主应用工程里面源代码新建qiankun/index.js,通信代码如下:

    import { initGlobalState } from "qiankun";
    import store from '@/store'
    
    // 主应用与微应用数据通信
    const state = {
      subappClassName: '' // 设置子应用打包根的class类名
    }
    const actions = initGlobalState(state);
    
    actions.setGlobalState(state);
    
    actions.onGlobalStateChange((state, prev) => {
      const { subappClassName } = state;
      store.dispatch('setSubappClassName',subappClassName);
      
    })
    export {
      actions
    };
    

    在主应用实例里面调用方式:

    <script>
    import actions from '@/qiankun'// 导入actions实例
    export default {
      created() {
        actions.setGlobalState({subappClassName: 'subapp'}); // 通过setGlobalState改变全局状态
      }
    }
    </script>
    

    子应用代码

    在子应用源代码utils/qiankun.js添加如下代码:

    class Actions {
      static empty() {
        console.warn('current actions is empty!')
      }
    
      actions = {
        onGlobalStateChange: Actions.empty,
        setGlobalState: Actions.empty
      }
    
      /** 初始化设置actions
       *
       */
      setActions(actions) {
        this.actions = actions;
      }
    
      onGlobalStateChange(...args) {
        return this.actions.onGlobalStateChange(...args);
      }
    
      setGlobalState(...args) {
        return this.actions.setGlobalState(...args);
      }
    }
    
    export default new Actions();
    

    在main.js入口文件引入actions实例,并在mount生命周期中导入该实例,代码如下:

    import actions from '@/utils/qiankun';
    export async function mount(props) {
      actions.setActions(props);
      actions.setGlobalState({ subappClassName: 'sub-root-app' }); // 可在mount中设置,也可在实例里设置
      render(props);
    }
    

    在vue路由页面调用:

    <script>
    import actions from '@/utils/qiankun.js';
    export default {
      created() {
        actions.setGlobalState({subappClassName: 'sub-root-app'});
      }
    }
    </script>
    
  • 相关阅读:
    Vue 面试题汇总
    SSIS 通过OData源连接Dynamic 365 Online
    SQL Server AlwaysOn
    SQL Server AlwaysOn
    SQL Server AlwaysOn
    SQL Server AlwaysOn
    OGG同步ORACLE至SQLSERVER(转)
    Power BI Online管理数据源
    SSRS 动态设置分组依据及行组个数
    查看Reporting Services服务器中用户查询报表历史记录
  • 原文地址:https://www.cnblogs.com/moqiutao/p/16349791.html
Copyright © 2020-2023  润新知