vite+vue3.0+ts配置单个使用svg图标

1、安装
npm install vite-plugin-svg-icons -D
2、在vite.config.ts中
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons';
const { resolve } = require('path');
plugins:[
    createSvgIconsPlugin({
      // 配置你存放 svg 图标的目录
      iconDirs: [resolve(process.cwd(), 'svg文件夹所在的目录')],//例如:src/images/svg
      // 定义 symbolId 格式
      symbolId: 'icon-[dir]-[name]',
    })
]
3、封装一个svg组件
<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconName" :fill="color"></use>
  </svg>
</template>

<script>
import { computed, defineComponent } from 'vue';
export default defineComponent({
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: '',
    },
    color: {
      type: String,
      default: '#889aa4',
    },
  },
  setup(props) {
    return {
      iconName: computed(() => `#icon-${props.iconClass}`),
      svgClass: computed(() => {
        if (props.className) {
          return `svg-icon ${props.className}`;
        }
        return 'svg-icon';
      }),
    };
  },
});
</script>

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

4、使用
//在main.ts中
import 'virtual:svg-icons-register';

①、使用时,如果想按需引入

// 在具体使用的地方
import SvgIcon from '组件地址'
  <svg-icon iconClass="${图标文件的名称}" class="*****"></svg-icon>
例如:arrow.svg   使用的时候iconClass ="arrow"

②、全局引入

//在main.ts中
import svgIcon from '组件地址';
app.component('svgIcon', svgIcon);
4、更改图标颜色

打开svg图标,把图标中的 fill="具体的颜色“ 改为 fill=currentColor
在页面中使用的时候,直接通过给fill赋值,来更改图标颜色的显示。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容