外观
getPx 单位转换
约 237 字小于 1 分钟
2024-01-01
介绍
提供单位转换功能,将rpx等单位转换为px单位。
getPx(value: string | number, unit?: boolean): number | string
- 参数
- value: 要转换的值,可以是数字或带单位的字符串
- unit: 是否返回带单位的字符串,默认 false
- 返回值
<Number|String>转换后的px值,如果unit为true则返回带px单位的字符串
示例代码
<template>
<view>
<text>单位转换示例</text>
<view :style="{ width: widthWithUnit, backgroundColor: '#007AFF', color: 'white', padding: '20rpx', marginBottom: '20rpx' }">
宽度: {{ widthWithUnit }}
</view>
<view :style="{ height: heightValue, backgroundColor: '#007AFF', color: 'white', padding: '20rpx', marginBottom: '20rpx' }">
高度: {{ heightValue }}px
</view>
</view>
</template>
<script setup lang="uts">
import { computed } from 'vue'
import { getPx } from '@/uni_modules/uview-unix'
// 直接转换rpx为px(不带单位)
const heightValue = computed(() => {
return getPx('200rpx')
})
// 转换为带px单位的字符串
const widthWithUnit = computed(() => {
return getPx(300, true)
})
console.log('300转换为带单位的px:', getPx(300, true)) // "300px"
console.log('200rpx转换为px:', getPx('200rpx')) // 转换后的px数值
</script>