欢迎扫码,加作者微信

阿里图标动态化导入

2025-08-07 02:40:42
2025-08-07 02:40:42

动态请求接口,获取CDN地址

language 复制代码
    // 从CDN链接提取font ID的函数
    const extractFontId = (url: string): string => {
      const match = url.match(/font_(\d+)_/);
      return match ? match[1] : ''; // 默认值
    };

    // 初始化iconfont
    async function initIconfont(): Promise<void> {
      try {
        // 从API获取CDN链接
        const res: any = await getAttrConfigDetail('iconfont_url');

        const url = res.data?.value;

        console.log('url', url);

        if (!url) {
          return;
        }

        // 根据CDN链接动态更新iconfontGlobalName
        const fontId = extractFontId(url);
        iconfontGlobalName.value = `_iconfont_svg_string_${fontId}`;

        console.log('fontId', fontId);

        // 动态创建script标签加载iconfont
        const script = document.createElement('script');
        script.src = url;
        script.async = true;

        // 设置script标签id
        script.id = 'iconfont';

        // 监听加载完成事件
        script.onload = () => {
          // 获取图标名称列表
          iconfontIcons.value = getIconfontNames();
          console.log('iconfontIcons', iconfontIcons.value);
        };

        script.onerror = () => {
          console.error('Failed to load iconfont:', url);
        };

        // 添加到head标签;
        document.head.appendChild(script);
      } catch (error) {
        console.error('Error initializing iconfont:', error);
      }
    }

    // 获取iconfont图标名称列表
    const getIconfontNames = (): string[] => {
      const globalName = iconfontGlobalName.value as keyof Window;
      const text = window[globalName] || '';
      return text.match(/(?<=id=")[^"]+(?=")/g) || [];
    };

渲染组件

language 复制代码
import SvgIcon from '@/components/SvgIcon/index.vue';
import { ElIcon } from 'element-plus';
import { h, type Component, type PropType } from 'vue';

export default defineComponent({
  name: 'BaseIcon',
  props: {
    name: {
      type: [String, Object] as PropType<string | Component | unknown>
    },
    size: {
      type: [String, Number]
    },
    color: {
      type: String
    }
  },
  setup(props) {
    return () => {
      return h(
        ElIcon,
        {
          size: props.size,
          color: props.color
        },
        () => {
          if (!props.name) {
            return;
          }
          if (typeof props.name === 'string') {
            if (props.name.startsWith('svg-')) {
              return h(SvgIcon, {
                name: props.name.slice(4)
              });
            }
            if (props.name.startsWith('icon-')) {
              return h(
                'svg',
                {
                  ariaHidden: true
                },
                h('use', {
                  'xlink:href': `#${props.name}`
                })
              );
            }
            return h(resolveComponent(props.name));
          }
          return h(props.name);
        }
      );
    };
  }
});
文章目录

生成中...

扫码赞赏

感谢您的支持与鼓励

安全支付

支付赞赏

您的支持是我们前进的动力

留言
快捷金额
自定义金额
¥

安全保障

采用银行级加密技术,保障您的支付安全

暂无评论,欢迎留下你的评论

暂无评论

期待您的精彩留言!
成为第一个评论的人吧 ✨

写下第一条评论
Copyright © 2025 粤ICP备19043740号-1
🎉 今日第 1 位访客 📊 年访问量 0 💝 累计赞赏 1000+