• 0
  • 0

uniapp 输入框最多保留两位小数

2020-02-25 792 0 admin 所属分类:Hbuilder

给表单输入框绑定变量和输入事件

<view class="form_item">
    <view class="form_title">退款金额
        <text class="text-red">*</text>
    </view>
    <view class="form_show">
        <input type="text" @input="input_return_amount" :value="return_amount" name="price" placeholder="输入要退款的金额" placeholder-style="color:#aaaaaa;" />
    </view>
</view>

在回调事件中处理

// 退款金额被输入
input_return_amount(e) {
    var actual = e.detail.value;
    //判断是否有小数点
    var pos = actual.indexOf('.')
    if (pos != -1 && pos != 0 && pos != (actual.length - 1)) {
        var s = actual.substr(0, pos);
        var s2 = actual.substr(pos + 1, 2);
        actual = s + '.' + s2;
        console.log(actual);
    }
    if (parseFloat(actual) > this.price) {
        app.Toast('退款金额不能超过订单总金额且保留0.01元')
        this.return_amount = this.return_order - 0.01
    } else {
        this.return_amount = '';
        this.return_amount = actual;
        console.log('this.return_amount', this.return_amount);
        this.$forceUpdate();
        return actual;
    }
}

需要注意的事貌似Vue对小数位变化不敏感,哪怕截取数据剩下两位都无法更新,调用 this.$forceUpdate();也无效因此需要将结果值return 回去。

返回顶部