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="symbolId" rel="external nofollow"  :fill="color" />
  </svg>
</template>

<script setup lang="ts">
import { computed } from &#39;vue&#39;;

const props = defineProps({
  prefix: {type: String,default: &#39;icon&#39;,},
  iconClass: {type: String,required: true,},
  color: {type: String,default: &#39;&#39;}
})

const symbolId = computed(() => `#${props.prefix}-${props.iconClass}`);
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  overflow: hidden;
  fill: currentColor;
}
</style>

三、tsconfig.json中添加设置

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

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

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

import { resolve } from &#39;path&#39;
import { createSvgIconsPlugin } from &#39;vite-plugin-svg-icons&#39;

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

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

import { createApp } from &#39;vue&#39;
import App from &#39;./App.vue&#39;
import router from &#39;@/router&#39;
import { store, key } from &#39;@/store&#39;

const app = createApp(App)

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

app.use(router).use(store, key).mount(&#39;#app&#39;)

六、在页面中使用

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

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

vue3+vite2中怎么使用svg方法

以上就是vue3+vite2中怎么使用svg方法的详细内容,更多请关注www.sxiaw.com其它相关文章!