<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简易计算器</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" placeholder="请输入第一个操作数" v-model.number="num1" />
<select v-model="opt">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" placeholder="请输入第一个操作数" v-model.number="num2" />
<button @click="xxx">计算</button><br>
methods方法:<strong>{{result}}</strong> <br>
computed计算属性:<strong>{{yyy}}</strong> <br>
watch监听器:<strong>{{ans}}</strong>
</div>
</body>
<script>
var vm = new Vue({
el: "#app",
data: {
num1: 0,
num2: 0,
ans: 0,
result: 0,
opt: "+"
},
methods: {//使用方法
xxx() {
this.result = eval(this.num1 + this.opt + this.num2);
/* switch (this.opt) {
case "+":
this.result = this.num1 + this.num2;
break;
case "-":
this.result = this.num1 - this.num2;
break;
case "*":
this.result = this.num1 * this.num2;
break;
case "/":
this.result = this.num1 / this.num2;
break;
} */
}
},
computed: {//计算属性
yyy() {
return eval(this.num1 + this.opt + this.num2);
/* switch (this.opt) {
case "+":
return this.num1 + this.num2;
case "-":
return this.num1 - this.num2;
case "*":
return this.num1 * this.num2;
case "/":
return this.num1 / this.num2;
} */
}
},
watch: {//监听器
num1(newNum, oldNum) {
console.log("num1:", oldNum, newNum);
this.ans = eval(this.num1 + this.opt + this.num2);
},
num2(newNum, oldNum) {
console.log("num2:", oldNum, newNum);
this.ans = eval(this.num1 + this.opt + this.num2);
},
opt(newOpt, oldOpt) {
console.log("opt:", oldOpt, newOpt);
this.ans = eval(this.num1 + this.opt + this.num2);
}
}
});
</script>
</html>
标签:opt,case,Vue,num1,num2,result,监听器,ans From: https://www.cnblogs.com/hyh6/p/17282808.html