前言
今天分享两种方法实现简单计算器
,使用者输入两个数字,点击按钮后,得出计算后的结果。
一、使用methods方法
<div id="app">
<!-- 第一个输入框 -->
<input type="number" v-model="prevValue" placeholder="请输入数字">
<!-- 请选择符号 -->
<select name="" id="" v-model="selected">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<!-- 第二个输入框 -->
<input type="number" v-model="nextValue" placeholder="请输入数字">
<!-- 计算按钮 -->
<button @click="count">=</button>
<!-- 计算结果 -->
<input type="number" v-model="scoreValue">
</div>
//实例化vue
const vm = new Vue({
//控制区域
el: '#app',
//存放数据
data: {
prevValue: '',
selected: '',
nextValue: '',
scoreValue: ''
},
//存放方法
methods: {
count() {
//使用switch判断选择的各种变量
switch (this.selected) {
case '+':
this.scoreValue = Number(this.prevValue) + Number(this.nextValue)
break;
case '-':
this.scoreValue = Number(this.prevValue) - Number(this.nextValue)
break;
case '*':
this.scoreValue = Number(this.prevValue) * Number(this.nextValue)
break;
case '/':
this.scoreValue = Number(this.prevValue) / Number(this.nextValue)
break;
}
}
}
})
虽然这个办法一目了然,但是相对于第二种办法是很笨重的。
二、使用eval()方法实现
<div id="app">
<!-- 第一个输入框 -->
<input type="number" v-model="prevValue" placeholder="请输入数字">
<!-- 请选择符号 -->
<select name="" id="" v-model="selected">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<!-- 第二个输入框 -->
<input type="number" v-model="nextValue" placeholder="请输入数字">
<!-- 计算按钮 -->
<button @click="count">=</button>
<!-- 计算结果 -->
<input type="number" v-model="scoreValue">
</div>
第二种办法的html代码没有变,但其js代码变得非常简单,只需要仅仅一行就能实现。
this.scoreValue = eval('Number(this.prevValue)' + this.selected + 'Number(this.nextValue)');
总结
以上就是今天要讲的内容。