简化版图书管理系统加减移除

  可以实现加减数量 计算总价  移除书籍 移除全部书籍之后 显示v-else “购物车为空

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>vue</title>
	<script src="js/vue.js"></script>
	<style>
	</style>
</head>

<body>
	<div id = "app">
		<div v-if="books.length">
			<table>
				<thead>
					<tr>
						<th></th>
						<th>书籍名称</th>
						<th>价格</th>
						<th>购买数量</th>
						<th>操作</th>
					</tr>
					
				</thead>
				<tbody>
					<tr v-for="(item,index) in books" :key="index">
						<td>{{item.id}}</td>
						<td>{{item.name}}</td>
						<td>{{item.price}}</td>
						<td>
							<button @click="add(index)">+</button>
							{{item.num}}
							<button @click="sub(index)">-</button>
						</td>
						<td><button @click="remove">移除</button></td>
					</tr>
				</tbody>
			</table>
		</div>
		<!-- 当书籍都移除之后 显示v-else -->
		<h2 v-else>购物车为空</h2>
		<h3>总价格{{tot}}</h3>
	
	</div>
	
	<script>
	var app = new Vue({
			el:"#app",
			data:{
				books:[
					{
						id:1,
						name:'算法计算',
						price:'10.00',
						num:'1'
					},
					{
						id:2,
						name:'加勒比海盗',
						price:'10.00',
						num:'1'
					},
					{
						id:3,
						name:'三天光明',
						price:'10.00',
						num:'1'
					},
					{
						id:4,
						name:'算法计算',
						price:'10.00',
						num:'1'
					}
				]
			},
			methods:{
				add:function(index){
					this.books[index].num++;
				},
				sub:function(index){
					this.books[index].num--;
				},
				//移除元素
				remove(index){
					this.books.splice(index,1)
				}
			},
			//计算总价
			computed:{
				tot:function(){
					let total = 0
					for (let i=0; i< this.books.length;i++){
						total += this.books[i].price * this.books[i].num
					}
					return total

                    //另一种写法 效果相同
					//let total = 0
					//for (let i in this.books) {
					//	total += this.books[i].price * this.books[i].num
					//}
					//return total
				}
			}
		})
	</script>

</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值