vue做购物车

写一点废话,昨天敲代码找bug,找了好久都没找到,后来一哥们找到他说,找代码的bug就像男女朋友吵架,女问男你错了没,男说错啦,女再问错哪了,男傻眼了不知道错哪。在找代码的过程中一直知道我错啦就是找不到错哪了,哈哈~~~~~~

正文

用vue知识点做购物车,

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<link rel="stylesheet" href="./bootstrap.min.css">
	<title>computed属性实现购物车</title>
	<style>
		body{
			padding-top:100px;
			text-align:center;
		}
		thead>tr>td{
			font-weight:bold;
		}
		.num,.total{
			display:inline-block;
			width: 120px;
		}
	</style>
</head>
<body>
	<div class="container">
		<table class="table table-hover table-bordered table-striped">
			<thead>
				<tr>
					<td>商品名称</td>
					<td>商品价格</td>
					<td>商品数量</td>
					<td>小计</td>
				</tr>
			</thead>
			<tbody>
				<tr v-for="(item,index) in products">
					<td>{{item.name}}</td>
					<td>{{item.price}}</td>
					<td>
						<button @click="decrease(index)">-</button>
						<span class="num">{{item.num}}</span>
						<button @click="increse(index)">+</button>
					</td>
					<td>
						<span class="total">{{item.price*item.num}}</span>
					</td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<td colspan="4" class="text-right">总价:{{total}}</td>
				</tr>
			</tfoot>
		</table>
	</div>
	<script src="vue.js"></script>
	<script>
		new Vue({
			el:".container",
			data:{
				products:[{
					name:"TV",
					price:2300,
					num:1
				},{
					name:"洗衣机",
					price:1500,
					num:1
				},{
					name:"拖鞋",
					price:20,
					num:2
				},{
					name:"iphone",
					price:9800,
					num:1
				}]
			},
			methods:{
				increse(index){
					this.products[index].num++
				},
				decrease(index){
					if(this.products[index].num===1)return
					this.products[index].num--
				}
			},
			computed:{
				total(){
					var sum=0;
					this.products.forEach(function(item){
						sum+=item.price*item.num;
					})
					return sum;
				}
			}
		})
	</script>
</body>
</html>
posted @ 2017-11-02 20:48  不完美的完美  阅读(680)  评论(0编辑  收藏  举报