最近在学习Vue的指令,做了一个简易计算器,比较适合刚入门的人参考学习。用到的知识点有:
1.插值表达式
2.v-model,双向绑定+、-、*、/、**等操作符
3.v-show,控制操作数2是否显示,乘方时不显示操作数2
4.methods选项,定义了calculate ()方法,实现各种运算
5.watch选项,监听selected的值的变化。
下面是程序的执行效果:
如果选择的是**乘方,操作数2不显示,这是利用v-show控制实现的,如图所示。
参考代码如下。
<!DOCTYPE html>
<html>
<head>
<title>项目2-1简易计算器</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div id="app">
<div class="calc">
<h3>简易计算器</h3>
<p> 操作数1 <input type="number" v-model="oper1" class="operand" /></p>
<p class="opera"> 运算符
<input type="radio" name="operator" value="+" v-model="selected">+
<input type="radio" name="operator" value="-" v-model="selected">-
<input type="radio" name="operator" value="*" v-model="selected">x
<input type="radio" name="operator" value="/" v-model="selected">➗
<input type="radio" name="operator" value="**" v-model="selected">**
</p>
<p>
<span v-show="isSeen">操作数2 <input type="number" v-model="oper2" class="operand" /></span>
</p>
<p> <button @click="calculate">计算=</button></p>
<div>
<div class="fs22">结果:{{result}}</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
const RootComponent = { //创建根组件
data() {
return {
isSeen: true,
selected: '',
oper1: '',
oper2: '',
result: '',
}
},
methods: {
calculate () {
if (this.selected === '') {
alert("请选择运算符")
return
}
switch (this.selected) {
case "+":
this.result = this.oper1 + this.oper2
break
case "-":
this.result = this.oper1 - this.oper2
break
case "*":
this.result = this.oper1 * this.oper2
break
case "/":
this.result = (this.oper1 / this.oper2).toFixed(2)
break
case "**":
this.result = this.oper1 * this.oper1
break
}
}
},
watch: {
selected(newValue, oldValue) {
if (newValue === "**") {
this.isSeen = false
} else {
this.isSeen = true
}
}
}
}
//创建Vue应用实例并挂载到#app
const vueApp = Vue.createApp(RootComponent)
vueApp.mount("#app")
</script>
<style>
.calc {
width: 600px;
margin: 0 auto;
}
.operand {
width: 120px;
height: 30px;
font-size: 20px;
}
.opera input {
margin-left: 20px;
}
button {
width: 80px;
height: 40px;
background-color: #339f63;
color: #fff;
font-size: 18px;
border-color: #ccc;
border-radius: 5px;
}
.fs22 {
font-size: 22px;
color: red;
}
</style>
</html>