vue3中使用svg并封装成组件

打包svg地图

  • 安装插件

    sh 复制代码
    yarn add vite-plugin-svg-icons -D
    # or
    npm i vite-plugin-svg-icons -D
    # or
    pnpm install vite-plugin-svg-icons -D
  • 使用插件

    vite.config.ts

    ts 复制代码
    import { VantResolver } from 'unplugin-vue-components/resolvers'
    +import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
    +import path from 'path'
    
    // https://vitejs.dev/config/
    export default defineConfig({
      plugins: [
        vue(),
        Components({
          dts: false,
          resolvers: [VantResolver({ importStyle: false })]
        }),
    +    createSvgIconsPlugin({
    +      // 指定图标文件夹,绝对路径(NODE代码)
    +      iconDirs: [path.resolve(process.cwd(), 'src/icons')]
    +    })
      ],
  • 导入到main

    ts 复制代码
    +import 'virtual:svg-icons-register'
  • 使用svg精灵地图

    html 复制代码
        <svg aria-hidden="true">
          <!-- #icon-文件夹名称-图片名称 -->
          <use href="#icon-login-eye-off" />
        </svg>

小结:

  • icons文件打包的产物?
    • 会生成一个 svg 结构(js创建的)包含所有图标,理解为 精灵图
  • 怎么使用svg图标?
    • 通过 svg 标签 #icon-文件夹名称-图片名称 指定图片,理解 精灵图定位坐标

【坑】vite-plugin-svg-icons报错:Cannot find package 'fast-glob'


自行安装一下fast-glob依赖解决该问题

sh 复制代码
yarn add fast-glob -D

图标组件-封装svg组件

组件 components/CpIcon.vue

html 复制代码
<script setup lang="ts">
// 提供name属性即可
defineProps<{
  name: string
}>()
</script>

<template>
  <svg aria-hidden="true" class="cp-icon">
    <use :href="`#icon-${name}`" />
  </svg>
</template>

<style lang="scss" scoped>
.cp-icon {
  // 和字体一样大
  width: 1em;
  height: 1em;
}
</style>

如果使用了 unplugin-vue-components 默认 src/compoenents 自动导入注册;

给组件添加类型,让写属性和事件可以有提示

类型 types/components.d.ts

ts 复制代码
// 1. 导入组件实例
import CpIcon from '@/components/CpIcon.vue'
// 2. 声明 vue 类型模块
declare module 'vue' {
// 3. 给 vue  添加全局组件类型,interface 和之前的合并
  interface GlobalComponents {
  // 4. 定义具体组件类型,typeof 获取到组件实例类型
  // typeof 作用是得到对应的TS类型
    CpIcon: typeof CpIcon
  }
}

使用:

html 复制代码
<template>
  <cp-icon name="login-eye-off"></cp-icon>
</template>
相关推荐
暗冰ཏོ17 小时前
《2026 Vue2 + Vue3 完整学习指南:基础语法、路由缓存、登录拦截、项目实战与面试题》
前端·vue.js·vue·vue3·vue2
曲幽2 天前
写页面时别再把 Element Plus 整个搬进来啦!Vue3按需加载的坑我帮你踩平了
vue3·web·vite·icon·element plus·vs code·import·unplugin
小云小白3 天前
若依-vue3 把深色版本改成天蓝色-含登录页
vue3·若依·天蓝色
曲幽4 天前
FastApiAdmin 后端接口开发好了,前端管理界面怎么调用与显示?
python·vue3·api·fastapi·web·ant design·view·menu·frontend
咬人喵喵7 天前
E2编辑器里的零高容器是什么?怎么用?
低代码·微信·编辑器·交互·svg
曲幽7 天前
我用了FastApiAdmin后,连夜把踩过的坑都整理出来了
redis·python·postgresql·vue3·fastapi·web·sqlalchemy·admin·fastapiadmin
Liu.7748 天前
vue3bug收录
vue3
需要坚持的人17 天前
让 SVG 不再“丢字变形”:一次思维导图导出文字转 Path 的实战优化
前端·vue.js·svg
小云小白17 天前
高性能 v-html 弹窗实现:Vue3 + Element Plus 最佳实践
vue3·弹窗·v-html
xun-ming18 天前
SpringBoot和Vue3实战阿里百炼大模型极简版
spring boot·ai·vue3·智能体·百炼大模型