想实现一个单位的自动换算,例如在千米表单中输入1,米和厘米自动显示在表单中;同理在厘米表单中输入数值,自动转换为千米和厘米
遇到问题:
好像不能实现另外两个的转换,就是说watch监听好像只能监听两个,添加厘米后千米转米和厘米可以,但米和厘米都不能转换为其他单位
<div id = "computed_props">
<h1>单位换算</h1>
千米 : <input type = "number" v-model = "kilometers">
米 : <input type = "number" v-model = "meters">
厘米:<input type = "number" v-model = "limeters">
</div>
<script>
var vm1 = new Vue({
el: '#computed_props',
data: {
kilometers : 0,
meters:0,
limeters:0
},
watch : {
kilometers:function(val) {
this.kilometers = val;
this.meters = this.kilometers * 1000;
this.limeters = this.kilometers * 100000;
},
meters:function (val) {
this.kilometers = val/1000;
this.meters = val;
this.limeters = val/100;
},
limeters:function(val){
this.limeters = val;
this.kilometers = val/ 100000;
this.meters = val/100;
}
}
});
</script>
是不是换成计算属性会更好?
按以上代码写法,当kilometers值改变时 会触发函数
kilometers:function(val) {
this.kilometers = val;
this.meters = this.kilometers * 1000;
this.limeters = this.kilometers * 100000;
},
而该函数 里面 修改了 this.meters 和 this.limeters,又会触发其他两个监听函数,所以达不到预期效果。
建议:不要使用v-model,而是将input的输入和设置值分开处理。
<template>
<div>
<input @input="inputChange('inputRef1')" ref="inputRef1"/>
<input @input="inputChange('inputRef2')" ref="inputRef2"/>
<input @input="inputChange('inputRef3')" ref="inputRef3"/>
</div>
</template>
<script>
export default {
data(){
return{
input1Val:'',
multiple:{'inputRef1':1, 'inputRef2':10, 'inputRef3':100},
}
},
methods:{
inputChange(inputRef){
let base = this.$refs[inputRef].value / this.multiple[inputRef];
for(let inputRef in this.multiple){
this.$refs[inputRef].value = base * this.multiple[inputRef];
}
}
}
}
</script>