vite2+Vue2: 使用svg-icon

812 阅读1分钟

Vue2.x尝试使用vite,使用svg-icon的一次实践,仅作记录

npm install vite-plugin-svg-icons -D // 安装处理svg的插件

在vite.config.js中配置

// vite.config.js
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";

export default defineConfig({
  plugins: [
    ...
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), "src/assets/icons")], // svg文件位置
      symbolId: "icon-[dir]-[name]"
    }),
  ]
});

svg-icon组件代码

<template>
  <svg class="svg-icon" :width="width" :height="height" aria-hidden="true">
    <use :xlink:href="iconName"></use>
  </svg>
</template>

<script>
export default {
  name: "svg-icon",
  props: {
    name: {
      type: String,
      required: true
    },
    width: {
      type: [String, Number],
      default: 24
    },
    height: {
      type: [String, Number],
      default: 24
    }
  },
  computed: {
    iconName() {
      return `#icon-${this.name}`;
    }
  }
};
</script>

<style lang="scss" scoped>
.svg-icon {
  overflow: hidden;
  fill: currentColor;
}
</style>

全局注册svg-icon组件

// main.js
import "virtual:svg-icons-register";

import SvgIcon from "./components/SvgIcon.vue";
Vue.component("svg-icon", SvgIcon);

ok,到这里就可以使用svg-icon组件了

// name即文件名
<svg-icon name="xxx"></svg-icon>
<svg-icon name="xxx" width="32" height="32"></svg-icon>