<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>简易计算器</title>
</head>
<body>
<!-- 挂载点 -->
<div id="sum">
<h1>简易计算器</h1>
<p><label>第一位数:<input type="number" v-model="num1"></label></p>
<p>
<label>运算符号:
<select v-model="oper">
<option value="1" selected>+</option>
<option value="2">-</option>
<option value="3">*</option>
<option value="4">/</option>
</select>
</label>
</p>
<p><label>第二位数:<input type="number" v-model="num2"></label></p>
<p style="font-size:12px;color:#ccc;">计算结果小数位大于5位时,精度有问题。</p>
<br>
<h2>{{result}}</h2>
</div>
<!-- <script src="vue.js"></script> -->
<script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>
<script>
new Vue({
//绑定挂载点
el : '#sum'
//数据模型
,data :{
//第一位数
num1 : 0
//第二位数
,num2 : 0
// 运算符
,oper : 1
// 结果显示
,result : 0
}
// 侦听器
,watch :{
num1 : function(){
this.result = calc(this.num1,this.num2,this.oper);
}
,num2 : function(){
this.result = calc(this.num1,this.num2,this.oper);
}
,oper : function(){
this.result = calc(this.num1,this.num2,this.oper);
}
}
});
// 运算
function calc(num1,num2,oper){
var res = 0;// 存储运算结果
//简单处理,转化
num1 = isNaN(parseFloat(num1)) ? 0 : parseFloat(num1);
num2 = isNaN(parseFloat(num2)) ? 0 : parseFloat(num2);
oper = isNaN(parseInt(oper)) ? 1 : parseInt(oper);
// swtich判断oper
switch(oper){
case 1:
res = num1 + num2;
oper = '+';
break;
case 2:
res = num1 - num2;
oper = '-';
break;
case 3:
res = num1 * num2;
oper = '*';
break;
case 4:
//简单进行处理
res = (isNaN(num1/num2) || !isFinite(num1/num2) ? 0 : (num1/num2));
oper = '/';
break;
default:
return '运算出错!';
break;
}
// 返回运算表达式及结果
return num1 + oper + num2 + '=' + res;
}
</script>
</body>
</html>