createCustomNameComponent.tsx 912 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * 后台返回的路由动态生成name 解决缓存问题
  3. * 感谢 @fourteendp
  4. * 详见 https://github.com/vbenjs/vue-vben-admin/issues/3927
  5. */
  6. import { Component, defineComponent, h } from 'vue';
  7. interface Options {
  8. name?: string;
  9. }
  10. export function createCustomNameComponent(loader: () => Promise<any>, options: Options = {}): () => Promise<Component> {
  11. const { name } = options;
  12. let component: Component | null = null;
  13. const load = async () => {
  14. try {
  15. const { default: loadedComponent } = await loader();
  16. component = loadedComponent;
  17. } catch (error) {
  18. console.error(`Cannot resolve component ${name}, error:`, error);
  19. }
  20. };
  21. return async () => {
  22. if (!component) {
  23. await load();
  24. }
  25. return Promise.resolve(
  26. defineComponent({
  27. name,
  28. render() {
  29. return h(component as Component);
  30. }
  31. })
  32. );
  33. };
  34. }