qiankun_Demo实践

主子应用对技术栈的选择

主应用: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()
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容