前言

本文介绍一种方法,用一段简洁的代码实现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 = Icons
  Object.keys(Icons).map(key => {
    app.component(key, Icons[key])
  })
}

那么在项目中需要使用icons时,第一步在./plugins/customComponents.js 文件中是否已经导入并注册,第二步是按照如下方法使用:

<template>
	<component :is="$icons['DeleteOutlined']"></component>
</template>
GitHub 加速计划 / vu / vue
207.54 K
33.66 K
下载
vuejs/vue: 是一个用于构建用户界面的 JavaScript 框架,具有简洁的语法和丰富的组件库,可以用于开发单页面应用程序和多页面应用程序。
最近提交(Master分支:2 个月前 )
73486cb5 * chore: fix link broken Signed-off-by: snoppy <michaleli@foxmail.com> * Update packages/template-compiler/README.md [skip ci] --------- Signed-off-by: snoppy <michaleli@foxmail.com> Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com> 4 个月前
e428d891 Updated Browser Compatibility reference. The previous currently returns HTTP 404. 5 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐