Vite + Vue2使用svg图标

Vite + Vue2使用svg图标


前言

vite-plugin-svg-icons

用于生成 svg 雪碧图.


提示:以下是本篇文章正文内容,下面案例可供参考

一、特征?

预加载 在项目运行时就生成所有图标,只需操作一次 dom
高性能 内置缓存,仅当文件被修改时才会重新生成

二、使用步骤

1.安装(yarn or npm)

node version: >=12.0.0
vite version: >=2.0.0

yarn add vite-plugin-svg-icons -D

or

npm i vite-plugin-svg-icons -D

2.使用

2.1 vite.config.ts 中的配置插件:

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

export default {
  plugins: [
    createSvgIconsPlugin({
      // 指定要缓存的图标文件夹
      iconDirs: [path.resolve(process.cwd(), 'src/icons/svg')],
      // 执行icon name的格式
      symbolId: 'icon-[dir]-[name]',
    }),
  ],
}

2.2 在 src/main.ts 内引入注册脚本:

import 'virtual:svg-icons-register';

3.如何在组件使用

3.1 /src/components/SvgIcon.vue

<template>
  <div v-if="isExternal" :style="styleExternalIcon" class="svg-external-icon svg-icon" v-on="$listeners" />
  <svg v-else :class="svgClass" aria-hidden="true" v-on="$listeners">
    <use :xlink:href="iconName" />
  </svg>
</template>

<script>
// doc: https://panjiachen.github.io/vue-element-admin-site/feature/component/svg-icon.html#usage
import { isExternal } from '@/utils/validate';

export default {
  name: 'SvgIcon',
  props: {
    iconClass: {
      type: String,
      required: true,
    },
    className: {
      type: String,
      default: '',
    },
  },
  computed: {
    isExternal() {
      return isExternal(this.iconClass);
    },
    iconName() {
      return `#icon-${this.iconClass}`;
    },
    svgClass() {
      if (this.className) {
        return 'svg-icon ' + this.className;
      } else {
        return 'svg-icon';
      }
    },
    styleExternalIcon() {
      return {
        mask: `url(${this.iconClass}) no-repeat 50% 50%`,
        '-webkit-mask': `url(${this.iconClass}) no-repeat 50% 50%`,
      };
    },
  },
};
</script>

<style scoped>
.svg-icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.svg-external-icon {
  background-color: currentColor;
  mask-size: cover !important;
  display: inline-block;
}
</style>

3.2 icons 目录结构

# src/icons/svg

- icon1.svg
- icon2.svg
- icon3.svg
- dir/icon1.svg

3.2 /src/App.vue

<template>
  <div>
    <SvgIcon name="user"></SvgIcon>
    <SvgIcon name="tree"></SvgIcon>
    <SvgIcon name="tree-table"></SvgIcon>
  </div>
</template>

<script>
import SvgIcon from './components/SvgIcon.vue';
export default{
  name: 'App',
  components: { SvgIcon },
};
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值