nvue开发中像素单位封装使用

官网注意点

注意点

这里我需要提醒的注意点有:
1、只支持flex布局,默认是纵向,需要设置则添加上flex-direction: row;
2、不支持%、vh、vw单位,支持rpx和px,推荐使用px
3、如果需要书写类名css,不能重叠,只能单独开辟一个类出来设置style

缘由

由于开发时候设计搞可能是以rpx为设置的单位,这个时候我们就需要通过计算占比来获取px的大小

封装一个获取px的方法

注意:高度请根据设计搞给于的高度进行设置,宽度rpx默认是750

export default {
	data(){
		return {
			screenHeight:0,
			screenWidth:0
		}
	},
  	onLoad() {
	    this.screenHeight = uni.getStorageSync('screenHeight');
	    this.screenWidth = uni.getStorageSync('screenWidth');
  	},
  	methods:{
	    /**
	     * @param {Number} num是设置的宽度值
	     */
	    getWidth(num) {
	      const width = this.screenWidth;
	      const a = num / 750; //计算rpx占比
	      const b = a * width; //通过px计算百分百的宽度
	      return b + 'px';
	    },
	    /**
	     * @param {Number} num是设置的高度值,最大421
	     */
	    getHeight(num) {
	      const height = this.screenHeight;
	      const a = num / 421; //这里我们设计搞事421rpx
	      const b = a * height;
	      return b + 'px';
	    },
	    /**
	     * 同事设置宽度和高度
	     * @param w是设置的宽度,h是设置的高度,如果都不填则默认是百分百
	     */
	    setWidthAndHeight(w, h) {
	      w = w ? this.getWidth(w) : this.screenWidth + 'px';
	      h = h ? this.getHeight(h) : this.screenHeight + 'px';
	      // console.log('测试====', h);
	      return {
	        width: w,
	        height: h
	      };
	    },
	}
}

使用

<!--宽高度百分百-->
<view class="container" :style="setWidthAndHeight()">
</view>

<!--高度百分百,宽度自行设置-->
<view class="left_bg" :style="{ width: getWidth(251), height: getHeight(421) }">

<!--left和right都是使用getWidth()-->
<!--top和bottom都是使用getHeight()-->
</view>
  • 6
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值