vue3中引入svg矢量圖
- 1、前言
- 2、安裝SVG依賴插件
- 3、在vite.config.ts 中配置插件
- 4、main.ts入口文件導入
- 5、使用svg
- 5.1 在src/assets/icons文件夾下引入svg矢量圖
- 5.2 在src/components目錄下創建一個SvgIcon組件
- 5.3 封裝成全局組件,在src文件夾下創建plugin/index.ts
- 5.4 在main.ts中引入plugin/index.ts文件
- 5.5 在頁面使用
1、前言
在項目開發過程中,我們經常會用到svg
矢量圖,而且我們使用svg
以后,頁面上加載的不再是圖片資源,這對頁面性能來說是個很大的提升,而且我們svg
文件比img
要小的很多,放在項目中幾乎不占用資源。
2、安裝SVG依賴插件
npm install vite-plugin-svg-icons -D
或
yarn add vite-plugin-svg-icons -D
或
pnpm install vite-plugin-svg-icons -D
3、在vite.config.ts 中配置插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {return {plugins: [createSvgIconsPlugin({iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],symbolId: 'icon-[dir]-[name]',}),],}
}
4、main.ts入口文件導入
import 'virtual:svg-icons-register'
5、使用svg
5.1 在src/assets/icons文件夾下引入svg矢量圖
5.2 在src/components目錄下創建一個SvgIcon組件
<template><svg :style="{ width, height }"><use :xlink:href="prefix + name" :fill="color"></use></svg>
</template><script setup>
defineProps({// 是否顯示prefix: {type: String,default: '#icon-',},name: String,color: {type: String,default: '#000',},width: {type: String,default: '16px',},height: {type: String,default: '16px',},})
</script><style lang='scss' scoped></style>
5.3 封裝成全局組件,在src文件夾下創建plugin/index.ts
//引入項目中的全局組件
import SvgIcon from '@/components/svgIcon.vue'//全局對象
const allGlobalComponents = { SvgIcon }//對外暴露插件對象
export default {install(app) {//注冊項目的全部組件Object.keys(allGlobalComponents).forEach((key) => {//注冊為全局組件app.component(key, allGlobalComponents[key])})},
}
5.4 在main.ts中引入plugin/index.ts文件
import GlobalComponents from '@/plugin'
app.use(GlobalComponents)
5.5 在頁面使用
<svg-icon name="tick" width="20px" height="20px"></svg-icon>