<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src="../lib/vue-2.4.0.js"></script>
</head>
<body>
<div id="app">
<input type="text" v-model="first" width="100px">
<select v-model="opt">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" v-model="second" width="100px">
<input type="button" value="=" @click="compute">
<input type="text" v-model="result" width="100px">
</div>
</body>
<script>
var vm = new Vue({
el: '#app',
data: {
first: '',
second: '',
result: '',
opt: '+'
},
methods: {
compute() {
switch (this.opt) {
case '+':
this.result = parseInt(this.first) + parseInt(this.second)
break
case '-':
this.result = parseInt(this.first) - parseInt(this.second)
break
case '*':
this.result = parseInt(this.first) * parseInt(this.second)
break
case '/':
this.result = parseInt(this.first) / parseInt(this.second)
break
}
}
}
});
</script>
</html>
总结:使用v-model实现双向数据绑定,不用操作DOM,在data中的数据为 String 类型,即使将其定义为数字,在methods 中的方法想使用时,this.first 也为 String 类型