外观
addUnit 添加单位
约 187 字小于 1 分钟
2024-01-01
介绍
为数值添加合适的单位,支持自动识别已有单位。
addUnit(value: string | number | null, unit?: string): string
- 参数
- value: 需要添加单位的值
- unit: 要添加的单位名称,默认为 'px'
- 返回值
<String>添加单位后的字符串
示例代码
<template>
<view>
<text>添加单位示例</text>
<button @click="testAddUnit">测试 addUnit 函数</button>
<view :style="{ width: widthStyle, height: heightStyle, backgroundColor: '#007AFF' }"></view>
</view>
</template>
<script setup lang="uts">
import { computed } from 'vue'
import { addUnit } from '@/uni_modules/uview-unix'
// 计算样式
const widthStyle = computed(() => {
return addUnit(300)
})
const heightStyle = computed(() => {
return addUnit(200, 'rpx')
})
const testAddUnit = () => {
console.log('添加px单位:', addUnit(100)) // "100px"
console.log('添加rpx单位:', addUnit(100, 'rpx')) // "100rpx"
console.log('已有单位:', addUnit('100%')) // "100%"
console.log('null值处理:', addUnit(null)) // ""
}
</script>