Vue初学习-简易购物车案例

2022-10-05 13:09:37

简易购物车最终效果:
在这里插入图片描述
实现功能如下:
数组的展示;
价格的格式要求为:¥xx.xx(保留两位小数);
当购买数量等于1时,减号按钮将不再能够点击;
总价格根据价格和数量进行计算而得;
点击移除按钮后,删除整行的内容(但未实现前面的id自动修改,此处使用的id是根据书籍绑定好了的);
当所有书籍都移除后,显示购物车为空,如下:
在这里插入图片描述
文件架构如图:
在这里插入图片描述

代码如下:
index.html

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>建议购物车</title><link rel="stylesheet" href="../css/style.css"></head><body><div id="app"><div v-if="books.length"><div><table><thead><tr><th></th><th>书籍名称</th><th>出版日期</th><th>价格</th><th>购买数量</th><th>操作</th></tr></thead><tbody v-for="(item, index) in books"><td>{{item.id}}</td><td>{{item.name}}</td><td>{{item.date}}</td><td>{{getFinalPrice(index)}}</td><td><button @click="decrement(index)":disabled="isOne(index)">-</button>{{item.count}}<button @click="increment(index)">+</button></td><td><button @click="removeClick(index)">移除</button></td></tbody></table></div><h2>总价格:{{totalPrice}}</h2></div><h2 v-else>购物车为空</h2></div><script src="../js/vue.js"></script><script src="../js/index.js"></script></body></html>

index.js

const app=newVue({
  el:'#app',
  data:{
    books:[{
        id:1,
        name:'《算法导论》',
        date:'2006-9',
        price:85.00,
        count:1},{
        id:2,
        name:'《UNIX编程艺术》',
        date:'2006-2',
        price:59.00,
        count:1},{
        id:3,
        name:'《编程珠玑》',
        date:'2008-10',
        price:39.00,
        count:1},{
        id:4,
        name:'《代码大全》',
        date:'2006-3',
        price:128.00,
        count:1},]},
  methods:{decrement(index){this.books[index].count--},increment(index){this.books[index].count++},isOne(index){if(this.books[index].count>1)returnfalsereturntrue},getFinalPrice(index){return'¥'+this.books[index].price.toFixed(2)},removeClick(index){this.books.splice(index,1)}},
  computed:{totalPrice(){let totalprice=0;for(let i=0; i<this.books.length; i++)
        totalprice+=this.books[i].price*this.books[i].countreturn'¥'+ totalprice.toFixed(2)}},})

vue.js可自行官网下载
在这里插入图片描述
style.css

table{border: 1px solid #e9e9e9;border-collapse: collapse;border-spacing: 0;}th, td{padding: 8px 16px;border: 1px solid #e9e9e9;text-align: left;}th{background-color: #f7f7f7;color: #5c6b77;font-weight: 600;}
  • 作者:langxiong_1009
  • 原文链接:https://blog.csdn.net/weixin_45899210/article/details/119355892
    更新时间:2022-10-05 13:09:37