主应用:

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

createApp(App).use(store).use(router).mount('#app')

import { registerMicroApps, start } from 'qiankun';

// 注册子应用
registerMicroApps([
  {
    name: 'child1', 
    entry: '//localhost:8081',
    container: '#yourContainer',
    activeRule: '/child/child1',         // 子应用触发规则(路径)
  },
]);
// 开启服务
start()

app.vue

<template>
  <div id="nav">
    主应用
    <!-- 子应用容器 -->
    <div id="yourContainer" style="width: 100%;border: 1px solid #ccc;"></div>
    <!-- 路由跳转 -->
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    <!-- 子应用路由跳转 -->
    <router-link to="/child/child1">child/child1</router-link>
  </div>
  <router-view/>
</template>

router index.ts

import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    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')
  }
]

console.log(process.env.BASE_URL)
const router = createRouter({
  // history: createWebHashHistory(),
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

子应用:

main.ts

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

const temp: any = window;
const isQiankun = temp.__POWERED_BY_QIANKUN__

export async function bootstrap() {
  console.log('react app bootstraped');
}

/**
 * 应用每次进入都会调用 mount 方法,通常我们在这里触发应用的渲染方法
 */
function render() {
  createApp(App).use(store).use(router).mount('#child1')
}
export async function mount(props: any) {
  console.log(props)
  render()
}
// createApp(App).use(store).use(router).mount('#child1')
/**
 * 应用每次 切出/卸载 会调用的方法,通常在这里我们会卸载微应用的应用实例
 */
export async function unmount(props: any) {
    console.log(props)
}

/**
 * 可选生命周期钩子,仅使用 loadMicroApp 方式加载微应用时生效
 */
export async function update(props: any) {
  console.log('update props', props);
}

isQiankun || render();

router index.ts

import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    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')
  }
]

const router = createRouter({
  history: createWebHistory('/child/child1'),
  // history: createWebHistory(process.env.BASE_URL),
  // history: createWebHashHistory(),
  routes
})

export default router

vue.config.js

const { name } = require('./package');

const port = 8081; // dev port
const dev = process.env.NODE_ENV === 'development'
module.exports = {
  publicPath: dev ? `//localhost:${port}` : '/',
  devServer: {
    port,
    headers: {
      'Access-Control-Allow-Origin': '*',
    },
  },
  // 自定义webpack配置
  configureWebpack: {
    output: {
      // 把子应用打包成 umd 库格式
      library: `${name}-[name]`,
      libraryTarget: 'umd',
      jsonpFunction: `webpackJsonp_${name}`,
    },
  },
};

index.html

<!DOCTYPE html>
<html lang="">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link rel="icon" href="<%= BASE_URL %>favicon.ico">
    <title><%= htmlWebpackPlugin.options.title %></title>
  </head>
  <body>
    <noscript>
      <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <!-- id不能与主应用重复 -->
    <div id="child1"></div>
    <!-- built files will be auto injected -->
  </body>
</html>

2021-12-27更新

上面的代码会出现偶发性的子应用中使用浏览器返回 url地址错误 导致无法返回页面的情况

修改子应用

router

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import View from '@/components/view/Index.vue'

const routes: Array<RouteRecordRaw> = [
  // {
  //   path: '/home',
  //   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: '/',
    redirect:'/qkcr-child1'
  },
  {
    path: '/qkcr-child1',
    component: View,
    redirect: '/qkcr-child1/home',
    name: 'qkcr-child1',
    meta: {
      title: 'qkcr-child1',
    },
    children: [
      {
        path: 'home',
        component: () => import(/* webpackChunkName: "system" */ '../views/Home.vue'),
        name: 'Home',
      },

      {
        path: 'about',
        component: () => import(/* webpackChunkName: "system" */ '../views/About.vue'),
        name: 'About'
      }
    ]
  }
]

const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL),
  // history: createWebHistory('/qkcr-child1'),
  history: createWebHistory('/'),
  routes
})

export default router

@/components/view/Index.vue 

<template>
  <router-view />
</template>

子应用中的路由相互跳转

<div id="nav">
    <router-link to="/qkcr-child1/home">Home</router-link> |
    <router-link to="/qkcr-child1/about">About</router-link>
  </div>

修改主应用

跳转到子应用

<router-link to="/qkcr-child1/about">qkcr-child1</router-link>

qiankun注册子应用

// 注册子应用
      registerMicroApps([
        {
          name: 'qkc-child1', 
          entry: '//localhost:8081',
          container: '#qiankunContainer',
          activeRule: '/qkcr-child1',         // 子应用触发规则(路径)
        },
      ]);
      // 开启服务
      start()

Logo

前往低代码交流专区

更多推荐