老师,我有几个问题
来源:3-23 自由编程
qq_慕哥8242320
2021-03-31 11:09:25
问题一:标签中v-model="inputValue1",inputValue1是变量对吧?但为什么到了侦听器watch这里,就改写成了函数名呢inputValue1()?
问题二:我的代码虽然能实现了功能,但我感觉还能优化,老师帮我看一下有哪些方面可以优化的
问题三:我直接把侦听器部分的代码删了也能实现功能,那么侦听器的作用在这里感觉没啥用
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model.number="inputValue1">
<select name="" id="" v-model="fuhao" @click="fuhaoClick">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" v-model.number="inputValue2">
<button @click="btnCumpted">=</button>
<input type="text" v-model.number="resultValue">
</div>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
inputValue1: "",//inputValue1是变量
fuhao: "",
inputValue2: "",
resultValue: ""
},
//侦听器watch:
//1. 需要侦听变量,如果侦听的变量不变化,就不会被执行
//2. 具备缓存机制,代码复杂
watch: {
inputValue1() { //这里怎么就变成同名函数了呢?
this.btnCumpted;//这里是为了侦听是否点击了bottom么
},
inputValue2() {
this.btnCumpted;
},
fuhao() {
this.btnCumpted;
}
},
methods: {
btnCumpted() {
switch(this.fuhao) {
case "+": this.resultValue = this.inputValue1 + this.inputValue2;break;
case "-": this.resultValue = this.inputValue1 - this.inputValue2;break;
case "*": this.resultValue = this.inputValue1 * this.inputValue2;break;
case "/": this.resultValue = this.inputValue1 / this.inputValue2;break;
}
},
fuhaoClick() {
switch(this.fuhao) {
case "+": this.resultValue = this.inputValue1 + this.inputValue2;break;
case "-": this.resultValue = this.inputValue1 - this.inputValue2;break;
case "*": this.resultValue = this.inputValue1 * this.inputValue2;break;
case "/": this.resultValue = this.inputValue1 / this.inputValue2;break;
}
}
}
})
</script>
</body>
</html>
1回答
好帮手慕星星
2021-03-31
同学你好,问题解答如下:
1、inputValue1是绑定的数据,也可以理解为变量。watch中固定用法,数据变为方法来使用,记住这样用就好

2、优化:符号处可以默认显示+,会更美观一些

3、侦听器没作用是因为btnCumpted为方法,需要调用才能使用。另外在select处也绑定了点击事件,所以写不写watch效果上没问题。
建议去掉select处绑定的点击事件,watch处监听fuhao改变即可


将fuhaoClick方法去掉

自己再测试下,祝学习愉快!
相似问题