我对以下模板中与v-model
一起使用Math.round()
有问题:
<v-text-field v-model="rounded" />
rounded
是一个计算属性:
rounded: {
get() {
return this.value;
},
set (val) {
this.value = Math.round(val);
console.log(this.value);
}
}
预期成果见v-text-field
:
Input | Expected Value | Actual Value
===============================================
1.12 | 1 | 1.12
1.6 | 2 | 2
为什么v-text-field
在我输入1.12
时不显示1
?
主要原因是,您正在更改值而不是舍入变量,因此,如果您像下面一样,希望您的问题能够解决。
<v-text-field v-model="rounded" :value="val" @change="OnChange" />
并将 val 属性添加到数据块中:
data(){
return:{
val:0.00
}
}
无需对计算属性执行任何操作,只需将 OnChange 方法写入方法块,如下所示:
methods:{
OnChange(newVal){
this.val = Math.round(newVal);
this. rounded=this.val;
}
}
不要绑定到计算属性,而是监视值并更新它。
<v-text-field v-model="rounded" />
{
data() {
return {
rounded: 0
}
},
watch: {
rounded(val) {
let newVal = Math.round(val);
if (newVal !== val) {
this.val = newVal
}
// or even simply this.val = Math.round(this.val) without the check ...
}
}
}