用Vue.js实现一个简易的购物车

2022-10-07 11:19:17

基于Vue.js实现一个简易的购物车

一、该案例主要实现功能功能
1.可以对商品进行更改数量,加减按钮。
(初始定义的数量为1,加操作正常进行,减操作当数量小于0时,减操作按钮不得使用)。
2.可以对每一项商品进行删除操作,当商品删除完后,会有一个显示购物车为空的提示字

下面就来展示一下代码:

<!DOCTYPE html><html><head><metacharset="utf-8"><title>书籍购物车</title><scripttype="text/javascript"src="../node_modules/vue/dist/vue.min.js"></script><styletype="text/css">table{width: 300px;height:80px;text-align: center;font-size: 12px;border-collapse: collapse;}table thead{height: 30px;background-color: #CCCCCC;opacity: 0.5;}table tbody{background:#D3D3D4;}</style></head><body><divid="app"><divv-if="books.length>0"><tableborder="1"cellspacing="1"cellpadding="1"><thead><tr><th></th><th>书籍</th><th>价格</th><th>数量</th><th>操作</th></tr></thead><tbody><trv-for="(value,index) in books"><td>{{value.id}}</td><td>{{value.book}}</td><td>{{value.price | singlePrice}}</td><!-- 过滤器写法 将value.price作为参数传进入到singlePrice函数中--><td><button@click="increment(index)">+</button>
							{{value.count}}<button@click="decrement(index)"v-bind:disabled="value.count<=1">-</button></td><td><button@click="del(index)">移除</button></td></tr></tbody></table><h1>总计价格是:{{getTotalprice()}}</h1></div><h2v-else>购物车为空!</h2></div></body><scripttype="text/javascript">const app=newVue({
			el:'#app',
			data:{
				books:[{
						id:1,
						book:'java书籍',
						price:120,
						count:1,},{
						id:2,
						book:'c++书籍',
						price:120,
						count:1},{
						id:3,
						book:'javascript书籍',
						price:120,
						count:1},{
						id:4,
						book:'python书籍',
						price:120,
						count:1}]},
			methods:{increment(index)//按钮加加操作{this.books[index].count++;},decrement(index)//按钮减减操作{this.books[index].count--;},del(index){this.books.splice(index,1);},getTotalprice()//价格总计{var sum=0;for(let i=0;i<this.books.length;i++){
						sum+=this.books[i].price*this.books[i].count;}return'¥'+ sum.toFixed(2);}},
			filters:{singlePrice(price){return"¥"+ price.toFixed(2);//toFixed是保留小数后几位}}})</script></html>

下面是效果演示:

在这里插入图片描述

  • 作者:枫叶在飘呀
  • 原文链接:https://blog.csdn.net/ld16631069828/article/details/116447802
    更新时间:2022-10-07 11:19:17