Vue3 antdv 如何动态渲染 icons-vue 图标(a-icon 不支持了)

2,142 阅读1分钟
  • vue3antdv 已经放弃 <a-icon type='xxx'> 的用法了。

  • antdv icon 官方文档 中有 正常的组件用法自定义方式的 iconfont 用法 ... 其中 iconfont 这种也是可以达到以前版本的 <a-icon /> 效果,只是图标都需要自行提供,如果想要直接使用官方新版本自带的所有 icon,只能另外的方式处理了。

  • 方式一:

    Vue3/React 动态设置 ant-design/icons 图标,推荐。

  • 方式二:

    // 初始化相关
    import { createApp } from 'vue'
    import { nextTick } from "@vue/runtime-core"
    
    // Antd
    import Antd from 'ant-design-vue'
    import 'ant-design-vue/dist/antd.css'
    import * as Icons from '@ant-design/icons-vue'
    
    // 创建对象
    const app = createApp(App)
    // 使用并挂载
    app.use(store).use(router).use(Antd).mount('#app')
    // 必须使用 nextTick,不然会有加载顺序问题,导致绑定失败
    nextTick(() => {
      // 配置全局对象
      app.config.globalProperties.$icons = Icons
      // Antd 注入全部图标(这样注入之后,就可以全局直接使用 icon 组件,不需要每个页面去引入了)
      for (const key in Icons) { app.component(key, Icons[key]) }
    })
    
    

    通过 <component :is="xxx" /> 动态使用,代替之前的 <a-icon type='xxx'>

    <!-- 动态使用(key 就是官方中拷贝的 icon 大驼峰写法,比如下面) -->
    <component :is="$icons['BugOutlined']" />
    <!-- 组件方式使用 -->
    <bug-outlined />