vue简易计算器

Original 2019-04-28 22:25:26 388
abstract:<!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>第一位数:<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>


Correcting teacher:天蓬老师Correction time:2019-04-29 09:15:23
Teacher's summary:vue.js, 做为一个前端的开发框架, 是成功的, 现在已经成为全球的三大框架之一, 关键一点是中文文档很丰富, 这与开发者本身也是华人有关

Release Notes

Popular Entries