使用computed,watch,methods三种方法
效果图:
步骤1:
导入连接js
<script src="js/vue.js"></script>
步骤2:
1 创建一个div
2 分别写computed,watch,methods三种方法
每个方法使用input标签制作输入框
符号的切换用select和option标签实现
<div id="app">
<!-- computed方法 -->
<input type="text" placeholder="请输入第一个数" v-model.number="num1">
<select v-model="sign">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" placeholder="请输入第二个数" v-model.number="num2"> <br>
结果是:{{num1}}{{sign}}{{num2}}={{res}} <br>
<!-- watch方法 -->
<input type="text" placeholder="请输入第一个数" v-model.number="num3">
<select v-model="sign1">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" placeholder="请输入第二个数" v-model.number="num4"> <br>
结果是:{{num3}}{{sign1}}{{num4}}={{res1}} <br>
<!-- methods方法 -->
<input type="text" placeholder="请输入第一个数" v-model.number="num5" @change="change">
<select v-model="sign2" @change="change">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" placeholder="请输入第二个数" v-model.number="num6" @change="change"> <br>
结果是:{{num5}}{{sign2}}{{num6}}={{res2}}
</div>
步骤3:
创建vue实例 连接app 写入三种方法的数据
<script>
const vm = new Vue({
el: "#app",
data: {
num1:0,
num2:0,
sign:"+",
num3:0,
num4:0,
sign1:"+",
res1:"0",
num5:0,
num6:0,
sign2:"+",
res2:"0"
},
})
</script>
步骤4:
写computed方法
computed:{
res(){
if(this.sign === "+") {
return this.num1 + this.num2;
} else if(this.sign === "-") {
return this.num1 - this.num2;
} else if(this.sign === "*") {
return this.num1 * this.num2;
} else if(this.sign === "/"){
return this.num1 / this.num2;
}
}
},
watch方法
watch:{
num3(val){
if(this.sign1 === "+") {
this.res1 = val + this.num4;
} else if(this.sign1 === "-") {
this.res1 = val - this.num4;
} else if(this.sign1 === "*") {
this.res1 = val * this.num4;
} else if(this.sign1 === "/"){
this.res1 = val / this.num4;
}
},
num4(val){
if(this.sign1 === "+") {
this.res1 = this.num3 + val;
} else if(this.sign1 === "-") {
this.res1 = this.num3 - val;
} else if(this.sign1 === "*") {
this.res1 = this.num3 * val;
} else if(this.sign1 === "/"){
this.res1 = this.num3 / val;
}
},
sign1(val){
if(val === "+") {
this.res1 = this.num3 + this.num4;
} else if(val === "-") {
this.res1 = this.num3 - this.num4;
} else if(val === "*") {
this.res1 = this.num3 * this.num4;
} else if(val === "/"){
this.res1 = this.num3 / this.num4;
}
}
}
methods方法
methods:{
change(){
if(this.sign2 === "+") {
this.res2 = this.num5 + this.num6;
} else if(this.sign2 === "-") {
this.res2 = this.num5 - this.num6;
} else if(this.sign2 === "*") {
this.res2 = this.num5 * this.num6;
} else if(this.sign2 === "/"){
this.res2 = parseInt(this.num5) / parseInt(this.num6);
}
}
},
这样用三种方法制作的计算机就完成啦