1. 创建IconFont组件
<template>
<svg class="icon" :style="iconStyle" aria-hidden="true">
<use :xlink:href="`#${name}`"></use>
</svg>
</template>
<script>
export default {
name: 'IconFont',
props: {
name: {
type: String,
required: true
},
size: {
type: [String, Number],
default: '16px'
},
color: {
type: String,
default: '#333'
}
},
computed: {
iconStyle() {
return {
width: typeof this.size === 'number' ? `${this.size}px` : this.size,
height: typeof this.size === 'number' ? `${this.size}px` : this.size,
fill: this.color
}
}
}
}
</script>
<style scoped>
:deep(.icon) {
width: 1em;
height: 1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
</style>
2. main.js全局注入
import Vue from 'vue'
import App from './App'
import IconFont from './components/custom-icons/iconfont.vue'
Vue.config.productionTip = false
App.mpType = 'app'
Vue.component('IconFont', IconFont)
const app = new Vue({
...App
})
app.$mount()
import { createSSRApp } from 'vue'
import App from './App.vue'
import IconFont from './components/custom-icons/iconfont.vue'
export function createApp() {
const app = createSSRApp(App)
app.component('IconFont', IconFont)
return {
app
}
}
3. app.vue引入
<script>
import '@/common/iconfont.js'
export default {
onLaunch: function() {
console.log('App Launch')
},
onShow: function() {
console.log('App Show')
},
onHide: function() {
console.log('App Hide')
}
}
</script>
4. 实例化-引用
<IconFont name="icon-xxx" :size="16" />
注意事项
- 确保项目中已经正确引入了 SVG 图标库文件(如 iconfont.js 或 iconfont.svg)
name
属性值必须与 SVG 图标库中的 symbol id 完全匹配- 组件支持响应式尺寸和颜色设置,可以根据业务需求动态调整
- 通过
aria-hidden="true"
属性,确保图标不会影响屏幕阅读器的阅读体验 - 小程序不支持symbol,推荐使用Font Class 方式 和 Symbol 方式
- Font Class 方式 和 Symbol 方式 仅支持单色,多色的要设置iconfont【字体设置】-彩色,设置彩色,原本单色的就改不了颜色