开篇

本篇的主题是在vue3项目中引入阿里图标库

步骤

注册阿里图标库账号(阿里图标),并创建项目

在这里插入图片描述

将图标加入项目中

  • 将需要的图标先加入购物车,随后加入到项目中
    在这里插入图片描述

生成项目代码

在项目中生成项目代码,便于后续复制到vue项目中
在这里插入图片描述## 在vue3项目中配置

  • 在App.vue中引入阿里图标库通用样式(只需要引入一次)
// 阿里图标库通用样式
.icon {
    width: 1em;
    height: 1em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
}
  • 在main.ts或main.js中,引入刚刚生成的项目代码

在这里插入图片描述

  • 按照需用封装一个通用的图标组件
<template>
  <div v-if="isColorIcon || isSvgIcon">
    <svg :style="setIconSVGStyle" aria-hidden="true" class="icon">
      <use :xlink:href="'#icon-' + name"></use>
    </svg>
  </div>
  <i v-else :class="getIconName" :style="setIconSvgStyle"/>
</template>

<script lang="ts" name="svgIcon" setup>
import {computed} from 'vue';

// 定义父组件传过来的值
const props = defineProps({
  // svg 图标组件名字
  name: {
    type: String,
  },
  // svg 大小
  size: {
    type: Number,
    default: () => 14,
  },
  // svg 颜色
  color: {
    type: String,
  },
  //彩色
  colorIcon: {
    type: Boolean,
    default: false,
  },
  // 是否是阿里图标库
  isSvg: {
    type: Boolean,
    default: false,
  }
});

// 在线链接、本地引入地址前缀
// https://gitee.com/lyt-top/vue-next-admin/issues/I62OVL
const linesString = ['https', 'http', '/src', '/assets', 'data:image', import.meta.env.VITE_PUBLIC_PATH];

// 获取 icon 图标名称
const getIconName = computed(() => {
  return 'iconfont icon-' + props?.name;
});
// 用于判断 element plus 自带 svg 图标的显示、隐藏
const isShowIconSvg = computed(() => {
  return props?.name?.startsWith('ele-');
});
// 用于判断在线链接、本地引入等图标显示、隐藏
const isShowIconImg = computed(() => {
  return linesString.find((str) => props.name?.startsWith(str));
});
// 设置图标样式
const setIconSvgStyle = computed(() => {
  return `font-size: ${props.size}px;color: ${props.color};`;
});
// 设置图片样式
const setIconImgOutStyle = computed(() => {
  return `width: ${props.size}px;height: ${props.size}px;display: inline-block;overflow: hidden;`;
});
// 设置图片样式
// https://gitee.com/lyt-top/vue-next-admin/issues/I59ND0
const setIconSvgInsStyle = computed(() => {
  const filterStyle: string[] = [];
  const compatibles: string[] = ['-webkit', '-ms', '-o', '-moz'];
  compatibles.forEach((j) => filterStyle.push(`${j}-filter: drop-shadow(${props.color} 30px 0);`));
  return `width: ${props.size}px;height: ${props.size}px;position: relative;left: -${props.size}px;${filterStyle.join('')}`;
});

const setIconSVGStyle = computed(() => {
  return `width: ${props.size}px;height: ${props.size}px;display: inline-block;overflow: hidden;`;
});
//是否是彩色图标
const isColorIcon = computed(() => {
  
  return props.colorIcon;
});
// 是否是阿里图标库
const isSvgIcon = computed(() => {
  
  return props.isSvg;
});
</script>

  • 在项目中使用该组件渲染图标
<SvgIcon :isSvg="true" :name="'row'"></SvgIcon>
  • 效果如下:
    在这里插入图片描述

注

值得一提的是,如果更新了项目中的图标,那么就需要更新图标项目的链接,并复制到vue3项目中。
感谢阅读!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐