vue3+vite2使用svg

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue3+vite2使用svg

zasulan   2022-09-28 我要评论

技术栈:vue3+vite2

前言:

写过一版基于vue-cli中使用svg的方法,但是因为webpack提供了require.context()在vite中无法使用,所以基于vite构建的项目则采取另一种方法

一、安装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 'vue';

const props = defineProps({
  prefix: {type: String,default: 'icon',},
  iconClass: {type: String,required: true,},
  color: {type: String,default: ''}
})

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 '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" style="width: 10em; height: 10em;border: 1px solid #000000;"></svg-icon>
</template>

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

八、参考链接地址

1、依赖官方参考文档:https://github.com/vbenjs/vite-plugin-svg-icons/blob/main/README.zh_CN.md

2、其中有一些内容点我根据该文章进行参考:https://www.cnblogs.com/haoxianrui/archive/2022/04/02/16090029.html

3、在vue-cli中使用svg的可以参考我另一篇文章:https:

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们