uniapp全局封装自定义icon使用iconfont组件(uview2修改很麻烦,自己封装一个)

##1、 在iconfont上下载需要的图标库
请添加图片描述

2、解压后把以下文件复制到项目中 static下请添加图片描述

请添加图片描述

3、在app.vue中引入样式,注意css存放位置,然后修改iconfont.css的路径


<style lang="scss">
	/* 注意要写在第一行,同时给style标签加入lang="scss"属性 */
	@import "uview-ui/index.scss";
	/*每个页面公共css */
	@import url("./static/font/iconfont.css");
</style>

在这里插入图片描述

4、组件编写,这里引入了部分uni自带的颜色与方法

<template>
    <view >
        <text  
		    :style="[iconStyle, $u.addStyle(customStyle)]" :class=" uClasses"></text>
    </view>
      
</template>

<script>
export default {
    name: '',
    props:{
         // 图标类名
         name: {
            type: String,
            default: ''
        },
        // 图标颜色,可接受主题色
        color: {
            type: String,
            default: uni.$u.props.icon.color
        },
        // 字体大小,单位rpx
        size: {
            type: [String, Number],
            default: uni.$u.props.icon.size
        },
        customStyle:{
            type:Object,
            default :() =>{}
        }
    },
    computed:{
        
			iconStyle() {
				let style = {}
				style = {
					fontSize: uni.$u.addUnit(this.size),
					lineHeight: uni.$u.addUnit(this.size),
					fontWeight: this.bold ? 'bold' : 'normal',
				}
				// 非主题色值时,才当作颜色值
				if (this.color && !uni.$u.config.type.includes(this.color)) style.color = this.color

				return style
			},
            uClasses (){
                let classes = []
                classes.push('text-icon-'+this.name,'text-icon')
                return classes.join(' ')
            },
            // 通过图标名,查找对应的图标
			icon() {
				// 如果内置的图标中找不到对应的图标,就直接返回name值,因为用户可能传入的是unicode代码
				return  this.name
			}
    },

    data() {
        return {
            
        };
    },

   
};
</script>




注意:代码中computed 中 uClasses text-icon 换成自己的样式前缀

5、全局组件引入,在main.js中


import myIcon from '@/components/myIcon/icon'
Vue.component("myIcon", myIcon);

6、组件使用

<myIcon name="fuzaliangbiao" color="red" size="36"></myIcon>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值