【前端學習之路】——去使用vue.js來編寫一個簡單的計算器

使用vue.js來編寫一個簡單的計算器

效果如圖所示:是一個十分簡單的計算器,包含了加減乘除,不是用原生js寫的,而是用vue.js寫的
在這裏插入圖片描述

html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</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>

js代碼:

<script src="js/vue.js"></script>
		<script>
			var vm=new Vue({
				el:"#app",
				data:{
					n1:0,
					n2:0,
					result:0,
					opt:"+"
				},
				methods:{
					//定義計算器算數的方法
					calc(){
						switch(this.opt){
							case "+":
								this.result=parseInt(this.n1)+parseInt(this.n2)
								//return this.result
								break;
							case "-":
								this.result=parseInt(this.n1)-parseInt(this.n2)
								//return this.result
								break;
							case "*":
								this.result=parseInt(this.n1)*parseInt(this.n2)
								//return this.result
								break;
							case "/":
								this.result=parseInt(this.n1)/parseInt(this.n2)
								//return this.result
								break;
						}
						
					}
				}
			})
		</script>
	</body>
</html>

不過在最後我使用了一個swith循環來設置這個,還有另一種方法,代碼量更少:
可以把裏面的循環改成:

//這是投機取巧,不要經常用 正是開發中,儘量少用
	var codeStr='parseInt(this.n1)'+this.opt+'parseInt(this.n2)'
	this.result=eval(codeStr)
發佈了18 篇原創文章 · 獲贊 19 · 訪問量 4162
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章