前言
本文介绍一种方法,用一段简洁的代码实现AntD Vue组件库的 icons 按需导入,只需在项目中导入一次,便可以随时使用,减小依赖体积。
场景
在官网的示例中,我们看到AntD Vue组件库升级到version@4.2.3之后,导入icons就是按需导入
<template><home-outlined />
</template><script setup>import { HomeOutlined } from '@ant-design/icons-vue';
</script>
需求
解决
在 ./plugins/customComponents.js
文件里导入所有第三方库的依赖,在进行全局注册,就可以在组件中随需随用,以下是该文件的示例:
import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'
import Highcharts from "highcharts"
import StockModule from "highcharts/modules/stock"
import FullscreenModule from "highcharts/modules/full-screen"
import HighchartsVue from "highcharts-vue"
import ExportingModule from "highcharts/modules/exporting"
import ExportDataModule from "highcharts/modules/export-data"
import {ExperimentOutlined,AreaChartOutlined,CloseOutlined,DeleteOutlined,DownloadOutlined,DotChartOutlined,EditOutlined,FullscreenOutlined,LineChartOutlined,LogoutOutlined,MenuUnfoldOutlined,MenuFoldOutlined,MinusCircleOutlined,PlusCircleOutlined,StarFilled,StarOutlined,TableOutlined,UserOutlined
} from "@ant-design/icons-vue"ExportingModule(Highcharts)
ExportDataModule(Highcharts)
FullscreenModule(Highcharts)
StockModule(Highcharts)Highcharts.setOptions({global: {useUTC: false,},
})/*** 全局注册自定义组件* @param app*/
export function setupCustomComponents(app) {app.use(VXETable)app.use(HighchartsVue)const Icons = {ExperimentOutlined,AreaChartOutlined,CloseOutlined,DeleteOutlined,DownloadOutlined,DotChartOutlined,EditOutlined,FullscreenOutlined,LineChartOutlined,LogoutOutlined,MenuUnfoldOutlined,MenuFoldOutlined,MinusCircleOutlined,PlusCircleOutlined,StarFilled,StarOutlined,TableOutlined,UserOutlined}app.config.globalProperties.$icons = IconsObject.keys(Icons).map(key => {app.component(key, Icons[key])})
}
那么在项目中需要使用icons时,第一步在./plugins/customComponents.js
文件中是否已经导入并注册,第二步是按照如下方法使用:
<template><component :is="$icons['DeleteOutlined']"></component>
</template>