Home > Article > Web Front-end > How to use svg method in vue3+vite2
You also need to install fast-glob related dependencies here, otherwise vite will report a Cannot find module 'fast-glob’ error when running npm run dev
npm i fast-glob@3.x -D npm i vite-plugin-svg-icons@2.x -D
<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>
types to specify the modules that need to be included , only the declaration files of the modules listed here will be loaded. It is not necessary to add it. When I tested the two demos, one required it and the other did not. If you have any problems, you can try adding
{ "compilerOptions": { "types": ["vite-plugin-svg-icons/client"] } }
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]', }) ] })
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>
The above is the detailed content of How to use svg method in vue3+vite2. For more information, please follow other related articles on the PHP Chinese website!