美文网首页
qiankun_Demo实践

qiankun_Demo实践

作者: 木子士心呦 | 来源:发表于2020-10-25 17:52 被阅读0次

    主子应用对技术栈的选择

    主应用:Vue + router(history)
    子应用:Vue + router(history)

    主应用配置

    使用Vue-cli3构建主应用项目。

    • 安装qiankun,在主应用的入口文件main.js中引入qiankun,并导入 registerMicroAppsstart.
    // 安装qiankun
    cnpm install qiankun -S
    
    // 在main.js中引入,并注册子应用配置
    import {registerMicroApps,start} from 'qiankun';
    registerMicroApps([
        name:'app name',
        entry:'//localhost:8001' // 子应用端口
        container:'#container', // 主应用上给子应用的容器
        activeRule:'/activeRule' // 主应用上当触发哪一个路由。才能在容器中加载该子应用
    ])
    // 运行
    start();
    
    • 在主应用页面中,跳转子应用页面,需要一个放子应用容器
    <template>
        <div>
            <button @click="goNext('/vue')">vue子应用</button>
            <div id="vue"></div>
        </div>
    </template>
    <script>
        methods:{
            goNext(router){
                window.history.pushState(null,router,router)
            }
        }
    </script>
    

    子应用配置

    使用Vue-cli3构建子应用项目。
    子应用不用安装qiankun,需用修改默认配置。

    • vue.config.js中,需要配置子应用可跨域,因为是通过fetch
    // vue.config.js
    devServer: {
        port: '8001',
        headers: {
          'Access-Control-Allow-Origin':'*'
        }
     }
     configureWebpack: {
        output: {
          library: 'vueApp',
          libraryTarget:'umd'
        }
        
     }
    
    • 在路由文件router/index.js中,需要修改base默认值。应该与主应用中配置的activeRule值相同。
    // router/index.js
    base:'/activeRule' 
    
    • 在子应用的入口文件main.js中,需要暴露三个生命周期函数,bootstrapmountunmount。在生命周期函数汇总调用应用的渲染函数。并且动态添加publicPath
    let instance = null
    
    function render() { 
      instance = new Vue({
        router,
        render: h => h(App)
      }).$mount('#app')
    }
    if (window.__POWERED_BY_QIANKUN__) { // 动态添加publicPath
      __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
    }
    if (!window.__POWERED_BY_QIANKUN__) { // 默认独立运行
      render();
    }
    export async function bootstrap() { }
    export async function mount(props) { 
      render(props)
    }
    export async function unmount() { 
      instance.$destroy()
    }
    

    相关文章

      网友评论

          本文标题:qiankun_Demo实践

          本文链接:https://www.haomeiwen.com/subject/kqynmktx.html