Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
Use Vue write simple calculator
- In the Vue, v-model instruction, and form elements can be achieved in two-way data binding Data Model, Next, we write a simple calculator with this directive, the following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<!--计算器的显示结构-->
<div id="app">
<input type="text" v-model="n1">
<select 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" value="=" @click="calculator">
<input type="text" v-model="result">
</div>
<script>
// 创建 Vue 实例,得到 ViewModel,简写vm
var vm = new Vue({
el: '#app',
data: {
n1: 0,
n2: 0,
opt: '+',
result: 0
},
methods: {
//计算的方法
calculator() {
switch (this.opt) {
case '+':
this.result = Number(this.n1) + Number(this.n2);
break;
case '-':
this.result = Number(this.n1) - Number(this.n2);
break;
case '*':
this.result = Number(this.n1) * Number(this.n2);
break;
case '/':
this.result = Number(this.n1) / Number(this.n2);
break;
}
}
}
});
</script>
</body>
</html>
- Results are as follows: