创建两个vue3 项目,并安装qiankun
vue create 'baseApp'
vue create 'vueApp'
npm i qiankun -S
主应用App.vue
<template>
<nav>
<router-link to="/">主应用Home</router-link> |
<router-link to="/about">主应用About</router-link>
</nav>
<router-view/>
<div id="vue"></div> //主要
</template>
主应用main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import { registerMicroApps, start } from 'qiankun';
registerMicroApps([
{
name: 'vueApp',
entry: '//localhost:8081', //启动子应用的地址
container: '#vue', //模板中的id
activeRule: '/vueApp', //启动子应用路由前缀
},
]);
// 启动 qiankun
start();
createApp(App).use(router).mount('#app')
在子应用src目录下创建 public-path.js
if (window.__POWERED_BY_QIANKUN__) {
window.__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
}
子应用 mian.js
import './public-path'
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
let instance = null
function render(props) {
const container = props?.container
instance = createApp(App).use(router).mount(container ? container.querySelector('#app') : '#app');
}
if (window.__POWERED_BY_QIANKUN__) {
__webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__
} else render()
export async function bootstrap() {
console.log('[vue] vue app bootstraped');
}
export async function mount(props) {
console.log('[vue] props from main framework', props);
render(props);
}
export async function unmount() {
console.log(instance.$el)
}
子应用 router
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import '../public-path'
const routes = [
{
path: '/',
name: 'home',
component: HomeView
},
{
path: '/about',
name: 'about',
component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
}
]
const router = createRouter({
history: createWebHistory(window.__POWERED_BY_QIANKUN__ ? '/vueApp/' : '/'), //如果是qinkun 以/vueApp/拼接路径
routes
})
export default router
子应用vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
headers: {
'Access-Control-Allow-Origin': '*',
},
},
configureWebpack: {
output: {
library: 'vueApp',
libraryTarget: 'umd', // 把微应用打包成 umd 库格式
//jsonpFunction: `webpackJsonp_${name}`,
},
},
})