Vue_使用v-model指令写的简易计算器
v-model指令对数据进行双向绑定
<body>
<div id="app">
<input type="text" v-model="n1">
<select name="" id="" v-model="opt">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" v-model="n2">
<input type="button" @click="calc" value="=">
<input type="text" v-model="result">
</div>
<script>
var vm = new Vue({
el: "#app",
data: {
n1: 1,
n2: 1,
result: 2,
opt: "+"
},
methods: {
calc() {
switch (this.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;
}
}
}
});
</script>
</body>
- 或者用eval()函数偷个懒
var strCode='parseInt(this.n1)'+this.opt+'parseInt(this.n2)';
this.result=eval(strCode);
eval()函数能不用就不用