iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >vue3+vite2中使用svg的方法详解(亲测可用)
  • 797
分享到

vue3+vite2中使用svg的方法详解(亲测可用)

vue3 vite2vue3.0 vitevue3使用svg图标 2022-11-13 14:11:38 797人浏览 安东尼
摘要

目录前言:一、安装vite-plugin-svg-icons二、在src/components/svgIcon下新建组件index.Vue三、tsconfig.JSON中添加设置四、

技术栈: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://www.jb51.net/article/258653.htm

总结

到此这篇关于vue3+vite2中使用svg的文章就介绍到这了,更多相关vue3+vite2使用svg内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: vue3+vite2中使用svg的方法详解(亲测可用)

本文链接: https://www.lsjlt.com/news/172226.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作