【uniapp】自定义图标symbol组件化

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全局注入


// #ifndef VUE3
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()
// #endif

// #ifdef VUE3
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
  }
}
// #endif

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" />

注意事项

  1. 确保项目中已经正确引入了 SVG 图标库文件(如 iconfont.js 或 iconfont.svg)
  2. name 属性值必须与 SVG 图标库中的 symbol id 完全匹配
  3. 组件支持响应式尺寸和颜色设置,可以根据业务需求动态调整
  4. 通过 aria-hidden="true" 属性,确保图标不会影响屏幕阅读器的阅读体验
  5. 小程序不支持symbol,推荐使用Font Class 方式 和 Symbol 方式
  6. Font Class 方式 和 Symbol 方式 仅支持单色,多色的要设置iconfont【字体设置】-彩色,设置彩色,原本单色的就改不了颜色
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值