Vue3 图标组件-打包svg地图

(一)解决性能问题:

实现:把icons目录下svg图片打包为精灵图使用

参考文档

1.安装插件

yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

2.使用插件

vite.config.ts

import { VantResolver } from 'unplugin-vue-components/resolvers'

// 自动引入组件,并按需引入组件的样式
+import Components from 'unplugin-vue-components/vite'
+import { VantResolver } from 'unplugin-vue-components/resolvers'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue(),
    Components({
      dts: false,
      resolvers: [VantResolver()]
    }),

    + // 自动引入并封装svg图片
    + createSvgIconsPlugin({
    +  // 指定图标文件夹,绝对路径(NODE代码)
    +  iconDirs: [path.resolve(process.cwd(), 'src/icons')]
    +})

  ]
})

3.导入到main.ts

// 注册图标
+import 'virtual:svg-icons-register'

4. vue模板中 使用svg精灵地图

  <!-- 1. 用image标签使用svg图,会造成图片的二次请求 -->
  <img src="@/icons/home/doctor.svg" />

  <!-- 2. 对所有svg图进行封装,使用svg图片 -->
  <svg aria-hidden="true">
    <!-- #icon-文件夹名称-图片名称 -->
    <use href="#icon-home-doctor" />
  </svg>

小结:用image标签使用svg图,会造成图片的二次请求

  • icons文件打包的产物

  • 会生成一个 svg 结构(js创建的)包含所有图标,理解为 精灵图

  • 使用svg图标

  • 通过 svg 标签 #icon-文件夹名称-图片名称 指定图片,理解 精灵图定位坐标

(二)图标组件二次封装-封装svg组件:

实现:把 svg 标签使用组件封装起来,方便重复使用方便。

1.组件 components/CpIcon.vue

<template>
  // 提供name属性即可
  <svg aria-hidden="true" class="cp-icon">
    <!-- #icon-文件夹名称-图片名称 -->
    <use :href="`#icon-${name}`" />
  </svg>
</template>

<script setup lang="ts">
defineProps<{
  name: string
}>()
</script>

<style scoped lang="scss">
// 根据父元素的字体大小来设置svg大小
.cp-icon {
  width: 1em;
  height: 1em;
}
</style>

2.类型 types/components.d.ts

// 1. 导入组件实例
import cpNavBar from '@/components/cp-nav-bar.vue'
+import cpIcon from '@/components/cp-icon.vue'

// 2. 声明 vue 类型模块
declare module 'vue' {
  // 3. 给 vue  添加全局组件类型,interface 和之前的合并
  interface GlobalComponents {
    // 4. 定义具体组件类型,typeof 获取到组件实例类型:typeof 作用是得到对应的TS类型

    cpNavBar: typeof cpNavBar
    +cpIcon: typeof cpIcon
  }
}

3.使用:

  <!-- 对icon svg进行组件化二次封装,方便使用; 根据父元素的字体大小来设置大小 -->
  <div style="font-size: 30px">
    <cp-icon name="home-doctor" />
  </div>

提示:

  • 有些图标可以根据 style 中 color 的值来设置颜色,图标是否有这个功能取决于 UI 做图片时否开启。

猜你喜欢

转载自blog.csdn.net/m0_73461567/article/details/129152106