最近闲暇无事研究下qiankun,发现最新的版本的接口与官网的文档不一致,估计文档还没梳理,故此在此记录下。主要更改的是注册时加入了container字段、loader函数。
-
container
微应用的容器 -
loader
加载函数(可不传),参数为loading和appContext,(实际中发现appContext始终为undefined),可以控制显示loading
具体使用详情见官方仓库的example
主项目是有VueCLI生成的普通的vue项目
主项目
1、安装qiankun
yarn add qiankun
2、编写qiankun.js逻辑,注册微应用
(由于主项目使用的是默认的hash
模式路由,故activeRule改为location.hash.startsWith(routerPrefix))
import { registerMicroApps, start, setDefaultMountApp } from 'qiankun'
function genActiveRule (routerPrefix) {
return location => location.hash.startsWith(routerPrefix)
}
export default function run () {
registerMicroApps([
{
name: 'react16',
entry: '//localhost:7100',
container: '#subapp-viewport',
loader: () => {},
activeRule: genActiveRule('#/react16')
},
{
name: 'react15',
entry: '//localhost:7102',
container: '#subapp-viewport',
loader: () => {},
activeRule: genActiveRule('#/react15')
}
])
setDefaultMountApp('/react16')
start()
}
注意由于我们配置的container为#subapp-viewport,故需要在构建路由时,在路由的componet中的template写入id为subapp-viewport的div
router.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/react16',
name: 'Home',
component: Home
},
{
path: '/react15',
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')
}
]
const router = new VueRouter({
routes
})
export default router
Home.vue中模板加入指定的dom元素
<template>
<div id="subapp-viewport">
</div>
</template>
<script>
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'
export default {
name: 'Home',
components: {
HelloWorld
}
}
</script>
main.js中引入qiankun.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import runApp from './qiankun'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
runApp()
子应用
子应用自己随便新建项目然后按照文档,导出生命周期钩子,加入publicPath即可,不然会导致404。
搞定~