10 vue中 v-model ,计算机demo

匿名 (未验证) 提交于 2019-12-03 00:15:02

A *B=C

A/B=C

基本逻辑是, 需要输入A 和B 得到C 。 选择运算符。 点击= 

所以页面布局分为几部分 

data: {
n1: 0, // A
n2: 0, //B
result: 0, //C
opt: '+' //运算符
},

A:

<input type="text" value="" v-model="n1">   ,A用v-model 绑定n1


<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>

<input type="text" value="" v-model="n2">   ,B用v-model 绑定n2

根据以上代码情况。 在methods中, 写入方法calc 。 由于是加减乘除格式,可以考虑2种方式

如下代码所示

methods: {
calc() { // 计算器算数的方法
// 逻辑:
switch (ths.opt) {
case '+':
this.result = parseInt(this.n1) + parseInt(this.n2)
break;
case '-':
this.result = parseInt(this.n1) - parseInt(this.n2)
break;
case '*':
this.result = parseInt(this.n1) * parseInt(this.n2)
break;
case '/':
this.result = parseInt(this.n1) / parseInt(this.n2)
break;
}
// 注意:这是投机取巧的方式,正式开发中,尽量少用
// eval ,将字符串解析执行拿到解析后的结果
var newStr =' parseInt(this.n1)' + this.opt + ' parseInt(this.n2)'
this.result = eval(newStr)
}
}

友情提示:不要忘记this哦!

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!