Vue案例-简单的购物车清单功能

vue简单的购物车功能

  • 目标:实现全选 当book的sel有变化时候都需要检测是否为全选
  • 目标:实现全选与反选
  • 目标:计算总价,总数量
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="./vue/vue.js" type="text/javascript" charset="utf-8"></script>
		<style type="text/css">
			input {
				width: 25px;
			}
		</style>
	</head>
	<body>
		<div id="app">
			<table border="" cellspacing="" cellpadding="">
				<tr>
					<th><input type="checkbox" @change="changeAll()" v-model="all"></th>
					<th>id</th>
					<th>名称</th>
					<th>日期</th>
					<th>价格</th>
					<th>数量</th>
					<th>操作</th>
				</tr>
				<tr v-for="item in books" :key="item.id">
					<td><input type="checkbox" v-model="item.sel"></td>
					<td>{{item.id}}</td>
					<td>{{item.name}}</td>
					<td>{{item.date}}</td>
					<td>${{item.price}}</td>
					<td>
						<button @click="cel(item,-1)" :disabled="item.num <=1">-</button>
						<input type="text" v-model="item.num" @input="check(item)">
						<button @click="cel(item,+1)" :disabled="item.num >=10">+</button>
					</td>
					<td><button @click="del(item)">删除</button></td>
				</tr>
			</table>
			<p>总价格:${{total.price}} 总数量:{{total.num}}</p>
		</div>
	</body>
	<script type="text/javascript">
		new Vue({
			el : "#app",
			data : {
				all : true,
				
				books : [
					{sel : true,id : 1,name : "小红书",price : 23,num : 1,date : "2019-30"},
					{sel : true,id : 2,name : "小4书",price : 22,num : 1,date : "2019-30"},
					{sel : true,id : 3,name : "小2书",price : 55,num : 1,date : "2019-30"},
					{sel : true,id : 4,name : "小0书",price : 33,num : 1,date : "2019-30"},
					{sel : true,id : 5,name : "小8书",price : 89,num : 1,date : "2019-30"}
				]
			},
			watch : {
				books : {
					handler : function() {
						this.all = this.books.every(item => item.sel);
						// 根据sel变化设置all的值
					},
					deep : true
				}
			},
			methods : {
				changeAll() {
					this.books.forEach(item => item.sel = this.all);
					// 遍历 books每个元素设置他的sel的值,为all的值
				},
				cel(item,n) {
					item.num += n;
					this.check(item);
				},
				// 判断如果输入框内的值到达多少使得状态
				check(item) {
					if(item.num <= 1) {
						item.num = 1;
					}
					if(item.num > 10) {
						item.num = 10;
					}
				},
				del(item) {
					var flag = window.confirm("确定删除吗?");
					// 判断点击确定时删除
					if(flag) {
						var ind = this.books.indexOf(item);
						this.books.splice(ind,1);
					}
				}
			},
			computed : {
				total : function() {
					var price = 0;
					var num = 0;
					this.books.forEach( item => {
						if(item.sel) {
							price += item.num * item.price;
							num += item.num *1;
						}
					})
					// 遍历books 如果sel为真的 ,累加数量 * 价格,以及商品的数量
					return ({price,num});
					// 返回一个对象,返回对象时需要用括号
				}
			}
		})
	</script>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34182705/article/details/106833322
今日推荐