微前端框架qiankun的备忘笔记。

之前工程中整合配置都成功了,两个月过去后,做新项目竟然又忘记怎么搞了,在此把相关内容做一下记录,避免再次出现这种尴尬的情况。

官方资料

参考项目

  1. https://github.com/F-loat/vue-cli-plugin-qiankun
  2. https://segmentfault.com/a/1190000024551391

代码示例

vue3的子应用实现

配置main.js和vue.config.js两个地方就可以了。

main.js

  1. // import './public-path';
  2. import { createApp } from 'vue';
  3. import { createRouter, createWebHashHistory } from 'vue-router';
  4. import App from './App.vue';
  5. import routes from './router';
  6. import store from './store';
  7. if (window.__POWERED_BY_QIANKUN__) {
  8. // eslint-disable-next-line no-undef
  9. __webpack_public_path__ = window.__INJECTED_PUBLIC_PATH_BY_QIANKUN__;
  10. }
  11. let router = null;
  12. let instance = null;
  13. function render(props = {}) {
  14. const { data, methods } = props;
  15. router = createRouter({
  16. history: createWebHashHistory(),
  17. routes,
  18. });
  19. instance = createApp(App);
  20. instance.use(router);
  21. instance.use(store);
  22. instance.mixin({
  23. data() {
  24. return {
  25. ...data,
  26. };
  27. },
  28. methods,
  29. });
  30. instance.mount('#biApp');
  31. }
  32. if (!window.__POWERED_BY_QIANKUN__) {
  33. render();
  34. }
  35. export async function bootstrap() {
  36. console.log('%c ', 'color: green;', 'vue3.0 app bootstraped');
  37. }
  38. function storeTest(props) {
  39. props.onGlobalStateChange &&
  40. props.onGlobalStateChange(
  41. (value, prev) => console.log(`[onGlobalStateChange - ${props.name}]:`, value, prev),
  42. true
  43. );
  44. props.setGlobalState &&
  45. props.setGlobalState({
  46. ignore: props.name,
  47. user: {
  48. name: props.name,
  49. },
  50. });
  51. }
  52. export async function mount(props) {
  53. console.log('mount props:', props);
  54. const methods = {};
  55. if (props.data.fns) {
  56. props.data.fns.forEach(item => {
  57. methods[item.name] = item;
  58. });
  59. delete props.data.funs;
  60. }
  61. storeTest(props);
  62. render({
  63. ...props,
  64. methods,
  65. });
  66. instance.config.globalProperties.$onGlobalStateChange = props.onGlobalStateChange;
  67. instance.config.globalProperties.$setGlobalState = props.setGlobalState;
  68. }
  69. export async function unmount() {
  70. instance.unmount();
  71. instance._container.innerHTML = '';
  72. instance = null;
  73. router = null;
  74. }

注意事项:

  1. 建议根组件挂载的元素id不要使用默认的#app,有可能会出现子应用覆盖了主应用的#app。

vue.config.js

  1. devServer: {
  2. hot: true,
  3. disableHostCheck: true,
  4. port,
  5. overlay: {
  6. warnings: false,
  7. errors: true,
  8. },
  9. headers: {
  10. 'Access-Control-Allow-Origin': '*',
  11. },
  12. proxy: {
  13. '/biconfigApi': {
  14. target: 'http://localhost:7001',
  15. changeOrigin: true,
  16. pathRewrite: { '^/biconfigApi': '/api' },
  17. },
  18. },
  19. },

注意事项:

  1. 注意写disableHostCheck和Access-Control-Allow-Origin,不然有可能会跨域加载不出来。
  2. api的前缀最好跟主应用的区分开来,不然有可能会被主应用捕捉走。

遇到的问题

  1. 在主应用的某个页面中,是否可以加载多个子应用的页面。