使用vue,html框架如下:<input type="text" class="no1"> <select id="ysf"> <option >+</option> <option >-</option> <option >*</option> <option >/</option> <option >%</option> </select> <input type="text" class="no2"> = <input type="text" class="jg"> <input type="button" value="计算" onclick="calc()"> ,完成双向绑定和计算功能
时间: 2023-07-19 08:40:40 浏览: 100
好的,我可以帮你完成这个任务。首先,你需要在 Vue 实例中定义几个数据属性,分别表示第一个输入框的值、第二个输入框的值、运算符和计算结果:
```javascript
new Vue({
el: '#app',
data: {
no1: '',
no2: '',
operator: '+',
result: ''
},
methods: {
calc: function() {
// 计算逻辑
}
}
})
```
然后,在 HTML 中使用 `v-model` 指令将这些数据属性与输入框绑定起来:
```html
<input type="text" class="no1" v-model="no1">
<select id="ysf" v-model="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
<option>%</option>
</select>
<input type="text" class="no2" v-model="no2">
= <input type="text" class="jg" v-model="result">
<input type="button" value="计算" @click="calc">
```
最后,在 `calc` 方法中编写计算逻辑,并将结果赋值给 `result` 数据属性:
```javascript
calc: function() {
var num1 = parseFloat(this.no1);
var num2 = parseFloat(this.no2);
if (isNaN(num1) || isNaN(num2)) {
this.result = '';
return;
}
switch (this.operator) {
case '+':
this.result = num1 + num2;
break;
case '-':
this.result = num1 - num2;
break;
case '*':
this.result = num1 * num2;
break;
case '/':
if (num2 === 0) {
this.result = '除数不能为0';
} else {
this.result = num1 / num2;
}
break;
case '%':
this.result = num1 % num2;
break;
}
}
```
这样就完成了双向绑定和计算功能。完整的代码如下:
```html
<div id="app">
<input type="text" class="no1" v-model="no1">
<select id="ysf" v-model="operator">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
<option>%</option>
</select>
<input type="text" class="no2" v-model="no2">
= <input type="text" class="jg" v-model="result">
<input type="button" value="计算" @click="calc">
</div>
<script>
new Vue({
el: '#app',
data: {
no1: '',
no2: '',
operator: '+',
result: ''
},
methods: {
calc: function() {
var num1 = parseFloat(this.no1);
var num2 = parseFloat(this.no2);
if (isNaN(num1) || isNaN(num2)) {
this.result = '';
return;
}
switch (this.operator) {
case '+':
this.result = num1 + num2;
break;
case '-':
this.result = num1 - num2;
break;
case '*':
this.result = num1 * num2;
break;
case '/':
if (num2 === 0) {
this.result = '除数不能为0';
} else {
this.result = num1 / num2;
}
break;
case '%':
this.result = num1 % num2;
break;
}
}
}
})
</script>
```
阅读全文