vue3+element-plus项目svg图标引入及使用

一、svg图标分为两种

一种是element-plus自带的el-icon图标,

另一种是第三方库的图标,我这里使用的阿里图标

二、封装成全局组件使用

1.下载安装

(1)element-plus的icon图标,目前是2.1.0版本

npm install @element-plus/icons-vue

(2)阿里的svg图标,我这里使用的2.0.1版本

npm i vite-plugin-svg-icons

2.目录结构,此时components中的组件均为全局组件

3. vite.config.ts

//引入阿里的svg需要用到插件
import path from "path";
import { createSvgIconsPlugin } from "vite-plugin-svg-icons";
plugins: [
    createSvgIconsPlugin({
      iconDirs: [path.resolve(process.cwd(), "src/assets/icons")],
      symbolId: "icon-[dir]-[name]",
    }),
]

4.svgIcon的index.vue文件

<template>
  <!-- svg:图标外层容器节点,内部需要与use标签结合使用 -->
  <svg :style="{ width, height }">
    <!-- xlink:href执行用哪一个图标,属性值务必#icon-图标名字 -->
    <!-- use标签fill属性可以设置图标的颜色 -->
    <use :xlink:href="prefix + name" :fill="color"></use>
  </svg>
</template>

<script setup lang="ts">
//接受父组件传递过来的参数
defineProps({
  //xlink:href属性值前缀
  prefix: {
    type: String,
    default: "#icon-",
  },
  //提供使用的图标名字
  name: String,
  //接受父组件传递颜色
  color: {
    type: String,
    default: "",
  },
  //接受父组件传递过来的图标的宽度
  width: {
    type: String,
    default: "16px",
  },
  //接受父组件传递过来的图标的高度
  height: {
    type: String,
    default: "16px",
  },
});
</script>

5.components的index.vue文件,将components中的文件遍历注册为全局组件

//引入项目中全部的全局组件
import SvgIcon from "./SvgIcon/index.vue";
//引入element-plus提供全部图标组件
import * as ElementPlusIconsVue from "@element-plus/icons-vue";
//全局对象
const allGloablComponent: any = { SvgIcon };
//对外暴露插件对象
export default {
  //务必叫做install方法
  install(app: any) {
    //注册项目全部的全局组件
    Object.keys(allGloablComponent).forEach((key) => {
      //注册为全局组件
      app.component(key, allGloablComponent[key]);
    });
    //将element-plus提供图标注册为全局组件
    for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
      app.component(key, component);
    }
  },
};

 6.main.ts

//svg插件需要配置代码
import "virtual:svg-icons-register";
//引入自定义插件对象:注册整个项目全局组件
import gloalComponent from "@/components";
//安装自定义插件
app.use(gloalComponent);

7.使用

    <el-icon><Plus /></el-icon>
    <svg-icon name="home" width="16px" height="16px" color="red"></svg-icon>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值