主应用
1、yarn add qiankun
2、修改app.vue的顶级id的值,如将app改成main-app(避免跟子应用的冲突)
3、在app.vue的<router-view></router-view>后面挂载上子应用,这里的id要对应main.js中的container
4、修改main.js的配置,其中
a、registerMicroApps的name要对应子应用的name,这个name要跟子应用的configureWebpack.output中的library的名称对应起来
b、entry: '//localhost:8099', 对应的就是子应用起来的端口
c、container: '#vue-app', 对应的是第3点
d、activeRule: '/active', 对应子分组的路径
app.vue
<template>
<div id="main-app">
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view> </router-view>
<div id="vue-app"></div>
</div>
</template>
main.js
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'sub-app', // app name registered
entry: '//localhost:8099',
container: '#vue-app',
activeRule: '/active',
},
]);
start();
子应用
vue.config.js
module.exports = {
devServer:{
port: 8099,
headers:{
"Access-Control-Allow-Origin":"*" //保证开发环境不会产生跨域问题
}
},
configureWebpack:{
output: {
library: `sub-app`,
libraryTarget: 'umd',
jsonpFunction: `webpackJsonp_sub-app`,
},
}
};
main.js
import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
Vue.config.productionTip = false;
let instance = null
function render() {
instance = new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
}
!window.__POWERED_BY_QIANKUN__&& (render()) //保证子应用能够独立运行
/**
* bootstrap 只会在微应用初始化的时候调用一次,下次微应用重新进入时会直接调用 mount 钩子,不会再重复触发 bootstrap。
* 通常我们可以在这里做一些全局变量的初始化,比如不会在 unmount 阶段被销毁的应用级别的缓存等。
*/
export async function bootstrap() {
console.log('react app bootstraped');
}
/**
* 应用每次进入都会调用 mount 方法,通常我们在这里触发应用的渲染方法
*/
export async function mount(props) {
console.log(props);
render()
console.log('zhlei xingma ')
}
/**
* 应用每次 切出/卸载 会调用的方法,通常在这里我们会卸载微应用的应用实例
*/
export async function unmount() {
instance.$destroy()
instance = null
}
/**
* 可选生命周期钩子,仅使用 loadMicroApp 方式加载微应用时生效
*/
export async function update(props) {
console.log('update props', props);
}
router==>index.js
import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import active from "../views/active.vue" //active组件
Vue.use(VueRouter);
const routes = [
{
path: "/",
name: "Home",
component: Home
},
{
path: "/about",
name: "About",
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () =>
import(/* webpackChunkName: "about" */ "../views/About.vue")
},
{ //对应主应用注册的路径
path:"/active",
name:'active',
component: active
}
];
const router = new VueRouter({
mode: "history",
// base: window.__POWERED_BY_QIANKUN__ ? '/' : '',
routes
});
export default router;
相应的active.vue
<template>
<div>
buyongpei
</div>
</template>
<script>
export default {
}
</script>
<style>
</style>