vue3+vite2中怎么使用svg方法

这篇文章主要介绍了vue3+vite2中怎么使用svg方法的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vue3+vite2中怎么使用svg方法文章都会有所收获,下面我们一起来看看吧。

一、安装vite-plugin-svg-icons

此处还需要安装下fast-glob相关依赖,不然vite运行npm run dev时会报Cannot find module 'fast-glob’的错误

npm i fast-glob@3.x -D
npm i vite-plugin-svg-icons@2.x -D

二、在src/components/svgIcon下新建组件index.vue

<template>
  <svg aria-hidden="true" class="svg-icon">
    <use :xlink:href=https://www.yisu.com/zixun/"symbolId" rel="external nofollow"  :fill="color" />
  




三、tsconfig.json中添加设置

types用来指定需要包含的模块,只有在这里列出的模块的声明文件才会被加载进来。非必要添加,我在两个demo测试的时候,一个需要一个不需要,若有问题可以尝试添加

{
  "compilerOptions": {
    "types": ["vite-plugin-svg-icons/client"]
  }
}

四、vite.config.ts 中的配置插件

import { resolve } from 'path'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
  plugins: [
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹
      iconDirs: [resolve(process.cwd(), 'src/assets/imgs/svg')],
      // 指定symbolId格式
      symbolId: 'icon-[dir]-[name]',
    })
  ]
})

五、在main.ts全局注册组件

import { createApp } from 'vue'
import App from './App.vue'
import router from '@/router'
import { store, key } from '@/store'

const app = createApp(App)

import 'virtual:svg-icons-register' // 引入注册脚本
import SvgIcon from '@/components/svgIcon/index.vue' // 引入组件
app.component('svg-icon', SvgIcon)

app.use(router).use(store, key).mount('#app')

六、在页面中使用

<template>
  <svg-icon icon-class="category"></svg-icon>
  <svg-icon icon-class="accountant" ></svg-icon>
</template>

七、文件目录结构及其效果展示

vue3+vite2中怎么使用svg方法

关于“vue3+vite2中怎么使用svg方法”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue3+vite2中怎么使用svg方法”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注行业资讯频道。

推荐HTML5使用SVG的方法

vue3+vite2中怎么使用svg方法