温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue3+vite2中怎么使用svg方法

发布时间:2022-08-09 17:14:53 来源:亿速云 阅读:368 作者:iii 栏目:开发技术

这篇文章主要介绍了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="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" ></svg-icon>
</template>

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

vue3+vite2中怎么使用svg方法

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI