VUE3 图片svgicon处理

220 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 7 天,点击查看活动详情

本文介绍vite-plugin-svg-icons 的组件引入,来更好的使用svg图片。 包安装的几种方式

yarn add vite-plugin-svg-icons -D
# or
npm i vite-plugin-svg-icons -D
# or
pnpm install vite-plugin-svg-icons -D

vite.config.ts 中的配置svg图片缓存位置等。

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
  base: './', //打包路径
  plugins: [
    vue(),
    // gzip压缩 生产环境生成 .gz 文件
    viteCompression({
      verbose: true,
      disable: false,
      threshold: 10240,
      algorithm: 'gzip',
      ext: '.gz',
    }),
    createSvgIconsPlugin({
      // 指定需要缓存的图标文件夹,所以要求我们将svg文件全部放在同一个文件夹里面。
      iconDirs: [path.resolve(__dirname, "src/assets/icons")],
      // 指定symbolId格式。
      symbolId: "icon-[dir]-[name]",

      /**
       * 自定义插入位置
       * @default: body-last
       */
      // inject?: 'body-last' | 'body-first'

      /**
       * custom dom id
       * @default: __svg__icons__dom__
       */
      // customDomId: '__svg__icons__dom__',

    })
  ],
  // 配置别名
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  }
})

svg图片都必须保存在vite.config.ts中配置的路径下 src/assets/icons路径下 src/assets/icons路径下

... icon.svg password.svg user_name.svg ...

svgicon组件用setup形式。

<template>
  <svg aria-hidden="true">
    <use :href="symbolId" :fill="props.color" />
  </svg>
</template>

<script setup lang="ts">
import { computed } from "vue-demi"
// setup 形式定义组件的属性,需要defineProps导出。当然也可以自定义width heght之类的。需求仅仅设置color和name就可满足
const props = defineProps({
//icon文件夹中svg图片的名称
    name: {
      type: String,
      required: true,
    },
    // 改变svg的颜色。
    color: {
      type: String,
      default: '#333',
    },
  })

const symbolId = computed(() => `#icon-${props.name}`)

</script>

<style scoped>
//默认会显示特别大,这个样式代码是关键,加入了才会显示正常。
svg {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>

使用 全局引用组件,在main.js中

import 'virtual:svg-icons-register'
// 全局引用组件
import SvgIcon from '@/components/SvgIcon/index.vue'
app.component('SvgIcon', SvgIcon)

使用的时候直接用

   <SvgIcon name="icon"></SvgIcon>
   <SvgIcon name="password"></SvgIcon>
      <SvgIcon name="user_name"></SvgIcon>


开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 7 天,点击查看活动详情