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>
相关推荐
明远湖之鱼3 天前
opentype.js 使用与文字渲染
前端·svg·字体
wsWmsw4 天前
[译] 浏览器里的 Liquid Glass:利用 CSS 和 SVG 实现折射
前端·css·svg
CodeCraft Studio5 天前
CAD文件处理控件Aspose.CAD教程:在 Python 中将 SVG 转换为 PDF
开发语言·python·pdf·svg·cad·aspose·aspose.cad
昔冰_G8 天前
Vue内置组件KeepAlive——缓存组件实例
vue.js·缓存·vue3·vue2·keep-alive·vue组件缓存·vue内置组件
wxr061610 天前
部署Spring Boot项目+mysql并允许前端本地访问的步骤
前端·javascript·vue.js·阿里云·vue3·springboot
知识分享小能手11 天前
微信小程序入门学习教程,从入门到精通,微信小程序开发进阶(7)
前端·javascript·学习·程序人生·微信小程序·小程序·vue3
红烧code16 天前
【Rust GUI开发入门】编写一个本地音乐播放器(4. 绘制按钮组件)
rust·gui·svg·slint
上单带刀不带妹16 天前
Vue3 全局 API 转移详解
前端·javascript·vue.js·vue3·api
吃饺子不吃馅17 天前
AntV X6图编辑器如何实现切换主题
前端·svg·图形学
雪山上的小灰熊18 天前
UNIAPP如何自定义全局方法?
javascript·typescript·uni-app·vue·vue3·vite·hooks