vue.js實現購物車功能

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>vue</title>
</head>
<style type="text/css">
	*{list-style: none;}
	table,tr,td,th{border: 1px solid #000;border-collapse: collapse;}
</style>
<body>
<div id="app">
	<table>
		<thead>
			<tr>
				<th>序號</th>
				<th>書名</th>
				<th>單價</th>
				<th>數量</th>
				<th>合計</th>
			</tr>			
		</thead>
		<tbody>
			<tr v-for = "(book,index) in goods">
				<td>{{index}}</td>
				<td>{{book.name}}</td>
				<td>{{book.price}}</td>
				<td><button @click="minus(index)" :disabled = "book.number===1" >-</button>{{book.number}}<button @click="add(index)">+</button></td>
				<td>{{book.price*book.number}}</td>
			</tr>
		</tbody>
	</table>	
	<p>總價:{{total}}</p>
</div>

<script type="text/javascript" src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<script type="text/javascript">
	var app = new Vue({
		el:'#app',
		data:{
			goods:[
				{name:"vue.js實戰",price:80,number:1},
				{name:"vue.js權威指南",price:60,number:3},
				{name:"vue.js2.0漸進式前端解決方案",price:50,number:2}
			]
		},
		methods:{
			minus :function(index){
				this.goods[index].number--;
			},
			add:function(index){
				this.goods[index].number++;
			}
		},
		computed:{
			total:function(){
				var arr = this.goods;
				var total = 0;
				for(var i = 0;i<arr.length;i++){
					total += arr[i].price*arr[i].number;
				}
				return total;
			}
		}
	});
</script>
</body>
</html>

  效果以下圖:javascript

相關文章
相關標籤/搜索