Vue之簡單的統計功能

                                    Vue之簡單的統計功能

今天我們來看看vue怎麼實現簡單的統計價格功能。

效果圖:

最後的價格自動根據選擇的項目來計算最終價格。

1.首先綁定每個項目綁定class 如果選中則增加樣式active,改變背景顏色 :class="{'active':item.active}"

2.寫計算事件,過濾掉集合中未選中的項目,在循環集合計算總價格。

全部代碼:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
    <title>Title</title>
</head>
<style type="text/css">
ul li{
	list-style: none;
	width: 200px;
	background-color: #e35885;
	margin-top: 5px;
	height: 40px;
	padding: 5px;
}
ul li strong{
	float: left;
	font-size: 20px;
}
ul li span{
	float: right;
	font-size: 20px;
	
}
ul li.active{
    background-color:#8ec16d;
}
</style>
<script src="vue.min.js"></script>
<body>
	<div id="test">
		<h1>Total</h1>
		<ul>
			<li v-for="item in phoneList" @click="item.active=!item.active" :class="{'active':item.active}"><strong>{{item.name}}</strong><span>{{item.price}}</span></li>
			
		</ul>
		<h1>FinalPrice:{{getTotal.totalPrice}}</h1>
	</div>
</body>
<script >
	new Vue({
		el : "#test",
		data : {
			phoneList:[
				{
					name:'apple',
					price : 5000,
					active :true
				},
				{
					name:'mi',
					price : 3000,
					active :false
				},
				{
					name:'sang',
					price : 4000,
					active :false
				},
				{
					name:'onePlus',
					price : 3500,
					active :false
				},
				{
					name:'oppo',
					price : 2000,
					active :false
				}
			]
		},
		computed:{
			getTotal :function(){
				var entry = this.phoneList.filter(function(val){return val.active})
				totalPrice = 0;
				for (var i = 0,len = entry.length; i < len; i++) {
					totalPrice +=entry[i].price;
				}
				return {totalPrice:totalPrice};
			}
		}
	})
</script>
</html>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章