之前分享过一篇文章,qiankun.js 微前端服务。这里的配置,当主应用的路由是hash时,就无法满足了。这里分享下,当主应用和子应用都是hash路由的解决办法:
主应用main.js配置:
import { registerMicroApps, start, initGlobalState } from 'qiankun' const getActiveRule = (hash) => (location) => location.hash.startsWith(hash) // 监听子应用发送的 closeTab事件 // 初始化 参数 state,state一定要起名初始化,这里我监听的是closeTab const actions = initGlobalState({ closeTab: '' }) actions.onGlobalStateChange((state, prev) => { // state: 变更后的状态; prev 变更前的状态 console.log('main state change', state, prev) // 将action对象绑到Vue原型上,为了项目中其他地方使用方便 // Vue.prototype.$actions = actions; // this.$actions.setGlobalState({ // mt: value // }) }) // 子应用注册信息 const apps = [ { name: 'workFlow', entry: '//localhost:8081', container: '#workFlow', activeRule: getActiveRule('#/jh-flow/'), props: { a: 1 } } ] registerMicroApps(apps) start()
子应用main.js配置:
let app = null function render(props) { app = new Vue({ router, store, render: (h) => h(App), }).$mount('#app') } if (window.__POWERED_BY_QIANKUN__) { __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__ } if (!window.__POWERED_BY_QIANKUN__) { render() } /** * @desctrption: 子应用初始化 */ export async function bootstrap(props) { console.log('[cbb] bootstrap') } /** * @desctrption: 子应用挂载 */ export async function mount(props) { // 设置通讯 Vue.prototype.$onGlobalStateChange = props.onGlobalStateChange; Vue.prototype.$setGlobalState = props.setGlobalState; render(props) } /** * @desctrption: 子应用卸载 */ export async function unmount() { console.log('[cbb] unmount') app.$destroy() app.$el.innerHTML = '' app = null router = null }
子应用路由配置:
const routes = [ { path: '/jh-flow/login', name: 'Login', component: Login, meta: { title: '登录' } }, { name: 'layout', path: '/jh-flow', component: Layout, redirect: '/jh-flow/dashboard', children: [ // 路由都加到这里 { name: 'dashboard', path: '/jh-flow/dashboard', component: Dashboard, children: [] } ] }, { path: '*', name: 'Err', component: NoFound, meta: { title: '404' } } ] const router = new VueRouter({ mode: 'hash', routes: routes })
子应用vue.config.js配置:
const { name } = require('./package') // qiankun.js 打包配置 module.exports = { devServer: { port: 8080, headers: { 'Access-Control-Allow-Origin': '*' } }, configureWebpack: { output: { library: `${name}-[name]`, libraryTarget: 'umd' } } }
主应用访问子应用url示例:
http://localhost:8080/#/jh-flow/login