vue实现图标加文字
在Vue中实现图标加文字
使用图标库(如Font Awesome)
安装Font Awesome库:
npm install @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons @fortawesome/vue-fontawesome
在Vue组件中使用:
<template>
<div>
<font-awesome-icon icon="user" />
<span>用户名</span>
</div>
</template>
<script>
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'
import { faUser } from '@fortawesome/free-solid-svg-icons'
export default {
components: {
FontAwesomeIcon
},
data() {
return {
icons: {
faUser
}
}
}
}
</script>
使用Element UI等UI框架
安装Element UI:
npm install element-ui
使用示例:
<template>
<div>
<el-button type="primary" icon="el-icon-user">用户</el-button>
</div>
</template>
<script>
import { Button } from 'element-ui'
export default {
components: {
'el-button': Button
}
}
</script>
自定义SVG图标
创建SVG图标组件:
<template>
<div class="icon-text">
<svg width="16" height="16" viewBox="0 0 24 24">
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/>
</svg>
<span>用户信息</span>
</div>
</template>
<style scoped>
.icon-text {
display: flex;
align-items: center;
gap: 8px;
}
</style>
使用CSS伪元素
通过CSS添加图标:
<template>
<div class="icon-text">用户</div>
</template>
<style scoped>
.icon-text {
position: relative;
padding-left: 20px;
}
.icon-text::before {
content: "";
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 16px;
height: 16px;
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm0 14.2c-2.5 0-4.71-1.28-6-3.22.03-1.99 4-3.08 6-3.08 1.99 0 5.97 1.09 6 3.08-1.29 1.94-3.5 3.22-6 3.22z"/></svg>');
background-size: contain;
}
</style>
动态绑定图标和文字
<template>
<div v-for="item in items" :key="item.id" class="icon-text">
<font-awesome-icon :icon="item.icon" />
<span>{{ item.text }}</span>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, icon: 'user', text: '用户中心' },
{ id: 2, icon: 'cog', text: '设置' },
{ id: 3, icon: 'bell', text: '通知' }
]
}
}
}
</script>






