在 UniApp 中,可以通过以下方法设置 input 组件的数值大小限制:
1. 使用 type="number" 和 max/min 属性
<template>
<view>
<input
type="number"
v-model="inputValue"
:max="100"
:min="0"
placeholder="请输入0-100之间的数字"
@input="handleInput"
/>
</view>
</template>
<script>
export default {
data() {
return {
inputValue: ''
}
},
methods: {
handleInput(e) {
let value = Number(e.detail.value)
// 手动限制数值范围
if (value > 100) {
this.inputValue = 100
uni.showToast({
title: '数值不能超过100',
icon: 'none'
})
} else if (value < 0) {
this.inputValue = 0
uni.showToast({
title: '数值不能小于0',
icon: 'none'
})
}
}
}
}
</script>
2. 使用正则表达式限制输入
<input
type="text"
v-model="inputValue"
@input="validateNumber"
placeholder="请输入0-100之间的数字"
/>
<script>
methods: {
validateNumber(e) {
let value = e.detail.value
// 只允许数字输入
value = value.replace(/[^\d]/g, '')
// 限制数值范围
if (value > 100) {
value = 100
uni.showToast({
title: '数值不能超过100',
icon: 'none'
})
}
this.inputValue = value
}
}
</script>
3. 使用计算属性自动修正
computed: {
limitedValue: {
get() {
return this.inputValue
},
set(value) {
let numValue = Number(value)
if (numValue > 100) {
this.inputValue = 100
} else if (numValue < 0) {
this.inputValue = 0
} else {
this.inputValue = value
}
}
}
}
主要要点:
type="number" 在移动端会调出数字键盘
max/min 属性提供基础限制
- 建议配合
@input 事件进行实时验证
- 使用
uni.showToast() 给用户反馈
选择哪种方法取决于你的具体需求和用户体验设计。