vite vue3 使用iconfont svg形式

1.登录https://www.iconfont.cn/ 官网,把自己喜欢得图标添加到项目中
2.按照标红的顺序选择把文件下载下来,下来以后解压缩把iconfont.js 放到项目中,注意js 文件中得fill='' 一定要为空字符
image
3.写一个全局svgIcon.vue组件

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconClassName" :fill="props.color" />
  </svg>
</template>

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

const props = defineProps({
  iconName: {
    type: String,
    required: true
  },
  className: {
    type: String,
    default: ""
  },
  //自定义颜色
  color: {
    type: String,
    default: "#ffffff"
  }
});

// 图标在 iconfont 中的名字

const iconClassName = computed(() => {
  return `#${props.iconName}`;
});

// 给图标添加上类名

const svgClass = computed(() => {
  if (props.className) {
    return `svg-icon ${props.className}`;
  }

  return "svg-icon";
});
</script>

<style scoped>
.svg-icon {
  width: 16px;
  height: 16px;
  position: relative;
  margin-right: 5px;
}
</style>

4.在 main.ts 中全局注册

// 引入阿里云字体js
import './assets/styles/icon/iconfont.js';
import SvgIcon from '@/components/svgIcon.vue'
const app = createApp(App)
app.component('SvgIcon',SvgIcon)

5.在具体业务中使用,例如菜单组件中使用如下

    <el-sub-menu
      :index="route.path"
      :key="route.name"
      :title="route.meta?.title || '未命名'"
    >
      <template #title>
        <svg-icon :iconName="route.meta.icon" />
        <span class="nav-text">{{ route.meta?.title }}</span>
      </template>
      <template v-for="children of route.children">
        <!-- 递归 -->
        <menuItem :route="children" />
      </template>
    </el-sub-menu>
posted @ 2022-12-15 18:10  火龙果呀  阅读(643)  评论(0)    收藏  举报