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>
相关推荐
Beginner x_u3 小时前
Vue3 + TS + TailwindCSS 操作引导组件开发逐行解析
typescript·vue3·前端开发·tailwindcss·组件开发
凯小默4 小时前
17-使用前置导航守卫判断用户登录后刷新情况
vue3
凯小默6 小时前
18-通过actions方法封装请求以及补充计算属性
vue3
凯小默2 天前
13-实现首页的基础结构
vue3
我叫张小白。2 天前
Vue3 插槽:组件内容分发的灵活机制
前端·javascript·vue.js·前端框架·vue3
是席木木啊2 天前
Vue3 + Axios 适配多节点后端服务:最小侵入式解决方案
vue3·axios·前端开发·技术方案设计
宁波阿成2 天前
基于Jeecgboot3.9.0的vue3版本前后端分离的flowable流程管理平台
vue3·springboot3·flowable·jeecgboot
盛夏绽放3 天前
新手入门:实现聚焦式主题切换动效(Vue3 + Pinia + View Transitions)
前端·vue3·pinia·聚焦式主题切换
我叫张小白。3 天前
Vue3 组件通信:父子组件间的数据传递
前端·javascript·vue.js·前端框架·vue3
凯小默3 天前
11-定义接口返回类型值
vue3