vue.js从入门到深入再到随心而用———利用v-model制作简易计算机

v-model的学习

1.效果

在两个输入框中分别输入数字,再选择做什么运算,最后按=号得到结果
在这里插入图片描述

2.代码

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript" src="../js/vue.min.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="calc"/>
			
			<input type="text" v-model="result" />
		</div>
		<script type="text/javascript">
			
		new Vue({
			el:'#app',
			data:{
				n1: 0,
				n2: 0,
				result: 0,
				opt: '+'
			},
			methods:{
				calc:function(){//计算方法
//					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)
				}
			}
		})
		</script>

	</body>
</html>

3. 要点

1.熟悉使用v-model双向绑定

原创文章 73 获赞 64 访问量 2742

猜你喜欢

转载自blog.csdn.net/qq_42147171/article/details/104952159
今日推荐