10 vue中 v-model ,计算机demo

计算机逻辑 

 A  +  B = C 

A -  B = C

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

 

<select v-model="opt">      运算符 + -  * / ,用v-model 绑定 opt
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>

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

 

<input type="button" value="=" @click="calc">  , 等号 = ,需要点击做运算, 使用点击事件click , 点击方法名称为 calc

 

<input type="text" v-model="result">  ,承载结果 result 

 

根据以上代码情况。 在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哦!

 

posted on 2019-10-16 12:26  执着的烙印  阅读(218)  评论(0编辑  收藏  举报

导航