vue3+vite2中使用svg的方法詳解(親測可用)
技術(shù)棧:vue3+vite2
前言:
寫過一版基于vue-cli中使用svg的方法,但是因為webpack提供了require.context()在vite中無法使用,所以基于vite構(gòu)建的項目則采取另一種方法
一、安裝vite-plugin-svg-icons
此處還需要安裝下fast-glob相關(guān)依賴,不然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中添加設(shè)置
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>
七、文件目錄結(jié)構(gòu)及其效果展示
八、參考鏈接地址
1、依賴官方參考文檔:https://github.com/vbenjs/vite-plugin-svg-icons/blob/main/README.zh_CN.md
2、其中有一些內(nèi)容點我根據(jù)該文章進行參考:https://www.cnblogs.com/haoxianrui/archive/2022/04/02/16090029.html
3、在vue-cli中使用svg的可以參考我另一篇文章:http://www.dbjr.com.cn/article/258653.htm
總結(jié)
到此這篇關(guān)于vue3+vite2中使用svg的文章就介紹到這了,更多相關(guān)vue3+vite2使用svg內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于導(dǎo)入、配置Vuetify遇到的幾個問題
這篇文章主要介紹了關(guān)于導(dǎo)入、配置Vuetify遇到的幾個問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06Vue中@keyup.enter?@v-model.trim的用法小結(jié)
這篇文章主要介紹了Vue中@keyup.enter?@v-model.trim的用法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-12-12Vue 清除Form表單校驗信息的解決方法(清除表單驗證上次提示信息)
這篇文章主要介紹了Vue 清除Form表單校驗信息的解決方法(清除表單驗證上次提示信息),本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04vue?eslint報錯:Component?name?“xxxxx“?should?always?be?
新手在使用腳手架時總會報各種錯,下面這篇文章主要給大家介紹了關(guān)于vue?eslint報錯:Component?name?“xxxxx“?should?always?be?multi-word.eslintvue的4種解決方案,需要的朋友可以參考下2022-07-07