Vue3 + Vite 项目使用 svg 加载 iconfont 的最佳实践

本文介绍了在Vue3+Vite项目中使用SVG图标(来自Iconfont)的方法,包括封装SvgIcon组件,通过iconfont.js引入图标,以及如何改变图标的hover效果。在封装组件时,通过props传递参数实现图标大小、颜色的动态调整,并在父组件中监听鼠标事件来修改hover状态。
摘要由CSDN通过智能技术生成

Vue3 + Vite 项目使用 svg 加载 iconfont 的最佳实践

1 为什么需要使用 iconfont?

一般情况下,Vue3 项目会搭配使用 Element Plus 组件 UI 库,因此大部分情况下可以直接使用其自带的图标 el-icon 。但是,有时候我们想要使用的图标在 el-icon 中不存在,这时就要寻找其他的图标库资源了(ps:大佬们可以自己设计绘画图标,doge~)。通常我们会使用 iconfont ——它是阿里巴巴提供的矢量图标管理、交流平台,提供了丰富的图标、插画以及字体资源。

2 如何在 Vue3 + Vite 项目中使用 iconfont?

2.1 封装 SvgIcon.vue 组件

src/component 文件夹下新建 SvgIcon.vue 文件,添加如下代码:

<template>
  <svg :class="svgClass" aria-hidden="true">
    <use :xlink:href="iconClassName" :fill="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: '#409eff'
  },
  size: {
    type: String,
    default: '1em'
  }
})
// 图标在 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 {
  /* v-bind 是 Vue3 才支持的功能,可以将 CSS 的值与 js 的值绑定 */
  width: v-bind('props.size');
  height: v-bind('props.size');
  position: relative;
  fill: currentColor;
  vertical-align: -2px;
}
</style>

组件封装好以后需要在 main.js 中全局注册一下,不然每次使用图标时还要单独引入一次该组件。

import { createApp } from 'vue'
import App from './App.vue'
import SvgIcon from './components/common/SvgIcon.vue'

const app = createApp(App)
app.component('SvgIcon', SvgIcon)
app.mount('#app')

2.2 引入 iconfont

进入 iconfont 官网,输入图标名后按下回车,如下图所示:
在这里插入图片描述
将鼠标悬浮到自己喜欢的图标上,然后点击添加入库图标,如下图所示:
在这里插入图片描述
然后点击导航栏购物车图标,然后在侧边栏中点击添加至项目按钮,如下图所示:
在这里插入图片描述
在这里插入图片描述
之后会自动跳转至个人项目页面,然后按下图进行点击:
在这里插入图片描述
将网页中的 js 代码全部选中后复制(按下键盘上的 Ctrl + A 后鼠标右键):
在这里插入图片描述
回到项目文件夹中在 src/assets 下新建 iconfont 文件夹,然后在其下面新建 iconfont.js 文件,最后把刚刚复制的 js 代码粘贴到该文件中。
在这里插入图片描述
然后在 main.js 中引入这个文件。

import './assets/iconfont/iconfont.js'

2.3 具体使用示例

直接在具体页面(.vue 文件)的 template 标签中使用即可。

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <svg-icon iconName="icon-like"></svg-icon>
  <svg-icon iconName="icon-star" color="green"></svg-icon>
</template>

2.4 如何改变图标的 hover 效果?

svg 图标不同于 class 样式,其无法直接通过修改 hover 样式来设置鼠标悬浮在图标上面时颜色改变,这个时候我们就需要换一种思路了。我们在 SvgIcon.vue 中传入了 color 属性,并且通过 fill 将 color 作用到 svg 图标上,因此我们可以在父组件中通过监听鼠标悬浮事件修改 color 的值来改变 hover 效果。

<template>
	<div class="icon-wrapper" @mouseenter="handleMouseenter" @mouseleave="handleMouseleave">
		<SvgIcon iconName="icon-star" :color="iconColor"></SvgIcon>
	</div>
</template>

<script setup>
const iconColor = ref('grey')
const handleMouseenter = () => {
    iconColor.value = 'blue'
}
const handleMouseleave = () => {
    iconColor.value = 'grey'
}  
</script>

3 附录

3.1 参考资料

  1. Vue3 + Vite + TS项目引入iconfont图标(Svg方式)
  2. Vue3+Element Plus使用svg加载iconfont的解决方案
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个基于 Vue3 和 Vite 的实现拖拽产生连线的代码示例: ```html <template> <div class="container"> <div class="box" v-for="(item, index) in boxes" :key="item.id" :style="{ top: item.top + 'px', left: item.left + 'px' }" @mousedown="mousedown(index)"> {{ item.name }} </div> <svg class="line-container"> <line v-for="(line, index) in lines" :key="index" :x1="line.x1" :y1="line.y1" :x2="line.x2" :y2="line.y2" /> </svg> </div> </template> <script> import { reactive, toRefs } from 'vue' export default { setup() { const state = reactive({ boxes: [ { id: 1, name: 'Box 1', top: 100, left: 100 }, { id: 2, name: 'Box 2', top: 200, left: 200 }, { id: 3, name: 'Box 3', top: 300, left: 300 }, ], lines: [], isDragging: false, currentBoxIndex: null, startX: null, startY: null, }) const mousedown = (index) => { state.isDragging = true state.currentBoxIndex = index state.startX = state.boxes[index].left state.startY = state.boxes[index].top } const mousemove = (event) => { if (state.isDragging) { const box = state.boxes[state.currentBoxIndex] box.left = state.startX + event.clientX - state.startX - box.width / 2 box.top = state.startY + event.clientY - state.startY - box.height / 2 } } const mouseup = () => { state.isDragging = false state.currentBoxIndex = null } const connectBoxes = () => { const lastBox = state.boxes[state.boxes.length - 1] const secondLastBox = state.boxes[state.boxes.length - 2] state.lines.push({ x1: secondLastBox.left + secondLastBox.width / 2, y1: secondLastBox.top + secondLastBox.height / 2, x2: lastBox.left + lastBox.width / 2, y2: lastBox.top + lastBox.height / 2, }) } return { ...toRefs(state), mousedown, mousemove, mouseup, connectBoxes, } }, mounted() { document.addEventListener('mousemove', this.mousemove) document.addEventListener('mouseup', this.mouseup) }, beforeUnmount() { document.removeEventListener('mousemove', this.mousemove) document.removeEventListener('mouseup', this.mouseup) }, } </script> <style> .container { position: relative; height: 500px; } .box { position: absolute; width: 100px; height: 100px; background-color: #ccc; text-align: center; line-height: 100px; user-select: none; cursor: move; } .line-container { position: absolute; width: 100%; height: 100%; pointer-events: none; } </style> ``` 代码中实现了一个简单的拖拽产生连线的功能,具体实现方式如下: 1. 在模板中使用 `v-for` 渲染出多个可拖拽的方块(`<div class="box">`)和一个 SVG 容器(`<svg class="line-container">`)来绘制连线; 2. 通过 `@mousedown` 监听鼠标按下事件,记录当前拖拽的方块的索引和起始位置; 3. 通过 `@mousemove` 监听鼠标移动事件,根据当前鼠标位置计算出方块的新位置; 4. 通过 `@mouseup` 监听鼠标抬起事件,清空当前拖拽状态; 5. 通过方法 `connectBoxes` 将最后两个方块连线。 需要注意的是,代码中通过 `reactive` 创建了一个响应式对象 `state`,并使用 `toRefs` 将其转换为响应式引用,以便在模板中使用。并且,在组件的 `mounted` 和 `beforeUnmount` 钩子中分别添加和移除了全局的鼠标移动和抬起事件监听器。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Vesuvius688

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值