uni-app uni-number-box使用踩坑记录(Vue3)

在 uni-number-box 输入数量,页面显示值修改了,但实际上打印时还是原来的值

代码如下:

<template>
	<view class="content">
		<view class="flex">
			<view>商品数量:</view>
			<uni-number-box ref="numberBox" background="#ffffff" v-model="quantity" :min="1" :max="999999999"
				@change="handleChange" @blur="handleBlur" />
			<view class="btn" @tap="handleSubmit">结算</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				quantity: 1
			}
		},
		methods: {
			handleChange(value) {
				setTimeout(() => {
					console.log('当前输入的值:' + value);
					console.log('实际上的值:' + this.quantity);
				})
			},
			handleBlur(e) {
				if (!e.detail.value || e.detail.value == '') {
					this.quantity = 1
				}
			},
			handleSubmit() {
				uni.showToast({
					title: '数量为:' + this.quantity,
					icon: 'none',
					duration: 3000
				});
			}
		}
	};
</script>

<style scoped>
	.content {
		padding: 20rpx;
		background-color: skyblue;
	}

	.flex {
		display: flex;
		justify-content: space-between;
	}

	.btn {
		width: 80rpx;
		height: 50rpx;
		text-align: center;
		line-height: 50rpx;
		background-color: #fff;
		color: black;
	}
</style>

效果如图:

解决办法:

1.1 在change事件中手动赋值

handleChange(value) {
	setTimeout(() => {
		this.quantity = value;
		console.log('当前输入的值:' + value);
		console.log('实际上的值:' + this.quantity);
	})
}

1.2 修改 uni-number-box 组件代码

由于操作加减按钮没有这个问题,所以我们先看看加减按钮绑定的事件

_calcValue(type) {
	if (this.disabled) {
		return;
	}
	const scale = this._getDecimalScale();
	let value = this.inputValue * scale;
	let step = this.step * scale;
	if (type === "minus") {
		value -= step;
		if (value < (this.min * scale)) {
			return;
		}
		if (value > (this.max * scale)) {
			value = this.max * scale
		}
	}

	if (type === "plus") {
		value += step;
		if (value > (this.max * scale)) {
			return;
		}
		if (value < (this.min * scale)) {
			value = this.min * scale
		}
	}

	this.inputValue = (value / scale).toFixed(String(scale).length - 1);
	this.$emit("change", +this.inputValue);
	// TODO vue2 兼容
	this.$emit("input", +this.inputValue);
	// TODO vue3 兼容
	this.$emit("update:modelValue", +this.inputValue);
}

我们可以看到这样一行代码

this.$emit("update:modelValue", +this.inputValue);

因为在 uni-number-box 中,并没有直接使用 props 传入过来的变量,而是用的变量 inputValue ,这行代码的作用则是在值变动时候,实现数据的双向绑定。

我们再看看 blur 事件中,并没有这样一行代码,我们自己加上就可以啦

_onBlur(event) {
	this.$emit('blur', event)
	let value = event.detail.value;
	if (!value) {
		// this.inputValue = 0;
		return;
	}
	value = +value;
	if (value > this.max) {
		value = this.max;
	} else if (value < this.min) {
		value = this.min;
	}
	const scale = this._getDecimalScale();
	this.inputValue = value.toFixed(String(scale).length - 1);
	this.$emit("change", +this.inputValue);
	this.$emit("input", +this.inputValue);
	this.$emit("update:modelValue", +this.inputValue); // 加上这行代码就可以啦
}

猜你喜欢

转载自blog.csdn.net/qq_39998026/article/details/127125048