vue 实现简单的计算器

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Cheng_May/article/details/81629044
<body>
		<div id="app">
			<h5> {{ msg }}</h5>
			<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="=" v-on:click="calc" />
			<input type="text" v-model="result" />
		</div>
	</body>
	<script >
		var vm = new Vue({
			el:'#app',
			data : {
				msg : '计算机',
			    n1 : 0,
			    n2 : 0,
			    result : 0,
			    opt : '+'
			},
			methods : {
				calc(){// 计算器算数的方法
					// 逻辑:
					switch(this.opt){
							case '+':
							this.result = parseInt(this.n1) + parseInt(this.n2);
						break;
							case '-':
							this.result = parseInt(this.n1) - parseInt(this.n2);
						break;
							case '*':
							this.result = parseInt(this.n1) * parseInt(this.n2);				
						break;
							case '/':
							this.result = parseInt(this.n1) / parseInt(this.n2);
						break;
					}
					//注意: 这是投机取巧的方式
				/*	var codeStr = 'parseInt(this.n1)' + this.opt + 'parseInt(this.n2)'					
					this.result = eval(codeStr);*/
				}
			}
		});

v-model是vue.js中唯一一个实现双向数据绑定的组件;

猜你喜欢

转载自blog.csdn.net/Cheng_May/article/details/81629044
今日推荐