vue3中引入svg矢量图

1、前言

在项目开发过程中,我们经常会用到svg矢量图,而且我们使用svg以后,页面上加载的不再是图片资源,这对页面性能来说是个很大的提升,而且我们svg文件比img要小的很多,放在项目中几乎不占用资源。

2、安装SVG依赖插件

npm install vite-plugin-svg-icons -Dyarn add vite-plugin-svg-icons -Dpnpm 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>

猜你喜欢

转载自blog.csdn.net/DZQ1223/article/details/134598983