1.0.4 • Published 2 years ago

vite-svg-icon v1.0.4

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

vite-svg-icon使用介绍

可以方便的在vue2和vue3中使用.svg文件

1、先进行安转引入

yarn add vite-svg-icon -D

2、在vite.config.js中配置

import { svgBuilder } from "vite-svg-icon";
export default defineConfig({
  build: {
    target: "es2015",
  },

  plugins: [
    svgBuilder("./aeeset/svg/"), // 这个是svg的文件目录
  ],
});

在vue3.0中使用

1、先定义组件 svgIcon.vue

<template>
  <svg :class="svgClass" v-bind="$attrs" :style="{ color: color, fontSize: size + 'px' }">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script setup>
  import { computed } from 'vue';

  const props = defineProps({
    name: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      default: '',
    },
    size: {
      type: String,
      default: '14',
    },
  });

  const iconName = computed(() => `#icon-${props.name}`);
  const svgClass = computed(() => {
    if (props.name) {
      return `svg-icon icon-${props.name}`;
    }
  });
</script>

<style lang="scss">
  .svg-icon {
    width: 1em;
    height: 1em;
    fill: currentColor;
    vertical-align: middle;
  }
</style>

2、在main.js中进行全局注册

import svgIcon from './components/svgIcon.vue';
const app = createApp(App);
app.component('svg-icon', svgIcon);

3、在页面中使用 name就是svg文件的名字

 <svg-icon name="qiye" size="30" color="black"></svg-icon>

vue2.0中引用

1、定义组件 svgIcon.vue

<template>
  <svg
    :class="svgClass"
    v-bind="$attrs"
    :style="{ color: color, fontSize: size + 'px' }"
  >
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
export default {
  props: {
    name: {
      type: String,
      required: true,
    },
    color: {
      type: String,
      default: "",
    },
    size: {
      type: String,
      default: "14",
    },
  },
  computed: {
    iconName() {
      return `#icon-${this.name}`;
    },
    svgClass() {
      if (this.name) {
        return `svg-icon icon-${this.name}`;
      }
      return "svg-icon";
    },
  },
};
</script>

<style lang="scss">
.svg-icon {
  width: 1em;
  height: 1em;
  fill: currentColor;
  vertical-align: middle;
}
</style>

2、全局注册组件

Vue.component('svg-icon', svgIcon)

使用方式和vue3.0的一致

常见问题

配置color属性之后 svg图标没有颜色改变

找到svg的源文件,将其中的 fill 属性删除,就可以改变颜色

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago