欢迎光临散文网 会员登陆 & 注册

Vue从零开始总结17

2021-04-15 20:08 作者:忘魂儿  | 我要投稿

实现简易购物车:

项目需求:有目录,有编号,数量可加减,有出版日期,总价格实时更新,不想要可以移除

html中

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Title</title>
 <link rel="stylesheet" href="index.css">
</head>
<body>
<div id="app">
 <table>
 <thead>
 <tr>
   <th></th>
   <th>书籍名称</th>
   <th>出版日期</th>
   <th>价格</th>
   <th>购买数量</th>
   <th>操作</th>
 </tr>
 </thead>
   <tbody>
   <tr v-for="(item,index) in books">
     <td>{{getId(item.id)}}</td>
     <td>{{getName(item.name)}}</td>
     <td>{{getDate(item.date)}}</td>
         <!--保留两个小数,自动作为参数传递给过滤器showPrice-->
         <td>{{item.price|showPrice}}</td>
     <td>
       <button @click="decrease(index)" :class="item.count<=0?'cloak':''">-</button>
       {{item.count}}
       <button @click="increase(index)">+</button>
     </td>
     <td><button @click="removeBtn(index)">移除</button></td>

   </tr>
   <tr :class="books.length==0?'cloak':''">
     <td>总价格:</td>
     <td>{{priceTotal.toFixed(2)}}</td>
   </tr>
   </tbody>
 </table>
</div>
<script src="../js/vue.js"></script>
<script src="index.js"></script>

</body>
</html>

js中

const app=new Vue({
 el:'#app',
 data:{
   books:[
     {
       id:1,
       name:'《算法导论》',
       date:'2001-01',
       price:85,
       count:1,
     } ,
     {
       id:2,
       name:'《LINUX编程》',
       date:'2001-01',
       price:59,
       count:1
     },
     {
       id:3,
       name:'《编程思想》',
       date:'2001-01',
       price:95,
       count:1
     },
     {
       id:4,
       name:'《代码简化》',
       date:'2001-01',
       price:128,
       count:1
     }
   ]
 },
 computed:{
   priceTotal(){
     let total=0;
     // for (const i in this.books) {
     //   total+=this.books[i].price*this.books[i].count;
     // }
     for (const item of this.books) {
       total+=item.price*item.count;
     }
     return total;
   }
 },
 methods:{
   increase(x)
   {
    if (x==this.books[x].id-1)
    {
      this.books[x].count++;
    }
   },
   decrease(y){
     if (y==this.books[y].id-1&&this.books[y].count>0)
     {
       this.books[y].count--;
     }
   },
   getId(id){
     return id;
   },
   getName(name){
     return name;
   },
   getDate(date){
     return date;
   },
   // getPrice(price){
   //   return '¥'+price.toFixed(2);
   // }
   removeBtn(z){
   this.books.splice(z,1);
   if (this.books.length==0){
     alert('购物车为空');
   }

   }
 },
 filters:{
   showPrice(price){
     return '¥'+price.toFixed(2);
   }
 }


})

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;
}
.cloak{
  visibility: hidden;
}

效果如下:


Vue从零开始总结17的评论 (共 条)

分享到微博请遵守国家法律