摘要:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>簡易計算器</title></head><body><!-- 掛載點 --><div id="sum&q
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>簡易計算器</title>
</head>
<body>
<!-- 掛載點 -->
<div id="sum">
<h1>簡易計算器</h1>
<p><label>第一位數(shù):<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>第二位數(shù):<input type="number" v-model="num2"></label></p>
<p style="font-size:12px;color:#ccc;">計算結(jié)果小數(shù)位大于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'
//數(shù)據(jù)模型
,data :{
//第一位數(shù)
num1 : 0
//第二位數(shù)
,num2 : 0
// 運算符
,oper : 1
// 結(jié)果顯示
,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;// 存儲運算結(jié)果
//簡單處理,轉(zhuǎn)化
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:
//簡單進(jìn)行處理
res = (isNaN(num1/num2) || !isFinite(num1/num2) ? 0 : (num1/num2));
oper = '/';
break;
default:
return '運算出錯!';
break;
}
// 返回運算表達(dá)式及結(jié)果
return num1 + oper + num2 + '=' + res;
}
</script>
</body>
</html>
批改老師:天蓬老師批改時間:2019-04-29 09:15:23
老師總結(jié):vue.js, 做為一個前端的開發(fā)框架, 是成功的, 現(xiàn)在已經(jīng)成為全球的三大框架之一, 關(guān)鍵一點是中文文檔很豐富, 這與開發(fā)者本身也是華人有關(guān)