VUE3--封装和使用SVG组件

184 阅读1分钟
安装依赖
npm install -D fast-glob
npm install -D vite-plugin-svg-icons

src/assets文件创建icons文件夹,里面存放svg图标

image.png

在main.ts中引入插件
// src/main.ts
import 'virtual:svg-icons-register'; // svg图标
在vite.config.ts中引入插件
import path from 'path
// 配置svg插件
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

export default defineConfig({
plugins: [
    ...
  // 其他插件配置
  createSvgIconsPlugin({
    // 指定需要缓存的图标文件夹
    iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
    // 指定symbolId格式
    symbolId: 'icon-[dir]-[name]'
  })
],
})
封装svg组件
// src/components/SvgIcon/index.vue
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="symbolId"></use>
  </svg>

</template>

<script setup lang="ts">
import {computed} from "vue";
const props = defineProps({
  prefix: {
    type: String,
    default: 'icon'
  },
  iconClass: {
    type: String,
    require: true,
  },
  className: {
    type: String,
    default: 'svg-icon'
  }
})

const symbolId = computed(() => {
  return props.iconClass? `#${props.prefix}-${props.iconClass}`: '#icon'
})

const svgClass = computed(() => {
  return props.className ? 'svg-icon ' + props.className : 'svg-icon'
})

</script>

<style scoped lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
使用svg组件
<template>
  <div class="w-full h-full login-wrap">
    <svg-icon icon-class="bgLogo" className="login-icon"></svg-icon>
  </div>
</template>

<script setup lang="ts">
import SvgIcon from "@/components/SvgIcon/index.vue"
</script>

<style scoped lang="scss">
.login-wrap {
  background-image: url("@/assets/images/bg.png");
  background-size: cover;

  .login-icon {
    width: 5rem;
    height: 5rem;
  }
}
</style>
最后的结果

image.png