1. 程式人生 > >Vue.js指令小練習001 列表點選計算價格

Vue.js指令小練習001 列表點選計算價格

需求如下: 在這裡插入圖片描述 分析: 點選li改變背景色加等於總價,再次點選還原背景色剪等於總價。

程式碼:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="vue.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			ul{
				background-color: gold;
				width: 275px;
				padding: 0px;
			}
			li{
				list-style: none;
				background-color: greenyellow;
				margin-top: 5px;
				height: 30px;
				line-height: 30px;
				padding-left: 15px;
				margin-left: 15px;
				width: 230px;
			}
			li:first-child{
				padding-top: 20px;
				text-align: center;
				width: 245px;
				padding-left: 0px;
				background-color: gold;
			}
			li:last-child{
				background-color: gold;
				border-top: 2px solid red;				
				padding-bottom: 20px;
			}
			span{
				float: right;
				margin-right: 15px;
			}
			.color{
				background-color: dodgerblue;
			}
		</style>
	</head>
	<body>
		<div id="div">
			<ul>
				<li>價格表</li>
				<li v-for = '(v,k) in arr' @click = 'fn(k)' v-bind:class ="{ color:v.bol }" >{{ v.name }}<span>單價:{{ v.price }}</span></li>
				<li>總價:<span>{{ prices }}</span></li>
			</ul>
		</div>	
		
	</body>
	<script type="text/javascript">
		var vm = new Vue({
			el:'#div',
			data:{
				arr:[
				{name:'蘋果',bol:false,price:200},
				{name:'橘子',bol:false,price:150},
				{name:'香蕉',bol:false,price:260},
				{name:'菠蘿',bol:false,price:200}
				],
				prices:0
			},
			methods:{
				fn: function(k){				
					this.arr[k].bol = !this.arr[k].bol;
					if(this.arr[k].bol == true){						
						this.prices += this.arr[k].price
					}
					if(this.arr[k].bol == false){						
						this.prices -= this.arr[k].price
					}
				}
			}
		});		
	</script>
</html>