Vue案例01-实现简易购物车

2022-10-13 11:29:37

咱废话不多说,先来看一下完成后的效果吧。

在这里插入图片描述

CSS 部分

这里没什么好说的,就是v-cloak 这一个知识点

table{border: 1px solid #e9e9e9;border-collapse: collapse;border-spacing: 0;}th,td{padding: 8px 16px;border: 1px solid #e9e9e9;text-align: center;}th{background-color: #f7f7f7;color: #5c6b77;font-weight: 600;}[v-cloak]{display: none;}

HTML部分

这里说明一些用到的一些Vue的知识点:

  1. v-if
  2. v-for
  3. v-cloak
  4. v-on > @
  5. v-bind > :
  6. 方法 methods
  7. 计算属性 computed
  8. 过滤器 filters
<!DOCTYPEhtml><htmllang="en"><head><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1.0"><title>购物车</title><linkrel="stylesheet"href="style.css"></head><body><divid="app"v-cloak><divv-if="books.length"><table><thead><tr><th></th><th>书籍名称</th><th>出版日期</th><th>价格</th><th>购买数量</th><th>删除</th></tr></thead><tbody><trv-for="(item,index) in books"><th>{{item.id}}</th><th>{{item.name}}</th><th>{{item.date}}</th><!--方案一 保留小数点和货币符号--><!-- <th>{{"¥"+item.price.toFixed(2)}}</th> --><!--方案二--><!-- <th>{{getFinalPrice(item.price)}}</th> --><!--方案三--><th>{{item.price | showPrice}}</th><th><button@click="decrement(index)":disabled="item.count<=0">-</button>
              {{item.count}}<button@click="increment(index)">+</button></th><th><button@click="removeHandle(index)">移除</button></th></tr></tbody></table><h2>总价格:{{totalPrice | showPrice}}</h2></div><h2v-else>
      购物车为空</h2></div></body><scriptsrc="../js/vue.js"></script><scriptsrc="main.js"></script></html>

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:50.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:{//这里我们放弃使用方法的形式来求总价格,转而使用计算属性,因为它的效率更高。// getFinalPrice(price){//   return "¥"+price.toFixed(2)// },increment(index){this.books[index].count++},decrement(index){this.books[index].count--},removeHandle(index){this.books.splice(index,1);}},computed:{totalPrice(){// 方案一:普通的for循环// let totalPrice = 0;// for(let i=0;i<this.books.length;i++){//   totalPrice += this.books[i].price * this.books[i].count// }// return totalPrice// 方案二:for in// let totalPrice = 0;// for(let i in this.books){//   // console.log(i);//1 2 3 4//   totalPrice += this.books[i].price * this.books[i].count// }// return totalPrice// 方案三:for of// let totalPrice = 0;// for(let item of this.books){//   // console.log(item);//这里拿到的就是数组里的每个对象//   totalPrice += item.price * item.count// }// return totalPrice// 方案四:reducereturnthis.books.reduce(function(preValue, book){// console.log(book);//分别输出四个对象return preValue+ book.price* book.count},0)}},// 过滤器filters:{showPrice(price){return"¥"+price.toFixed(2)}}})
  • 作者:优雅哥cc
  • 原文链接:https://blog.csdn.net/weixin_43742708/article/details/107583156
    更新时间:2022-10-13 11:29:37