vue购物车案列

旧时模样 提交于 2020-03-08 14:19:55
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>
  <div id="payFor">
    <div v-if="this.books.length">
  <table>
    <thead>
      <tr>
        <th></th>
        <th>书籍名称</th>
        <th>出版日期</th>
        <th>价格</th>
        <th>购买数量</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(items,index) in books">
        <td>{{items.id}}</td>
        <td>{{items.name}}</td>
        <td>{{items.date}}</td>
        <td>{{items.price|showPrice}}</td>
        <td>
          <button @click="decreme(index)">-</button>
          {{items.count}}
          <button @click="increme(index)">+</button>
        </td>
        <td><button @click="removeHandle">移除</button></td>
      </tr>
    </tbody>
  </table> 
 <h2>总价格:{{totalPrice|showPrice}}</h2>
</div>
<h2 v-else>购物车为空</h2>
  </div>
  <script src="./../../vue.min.js"></script>
  <script src="./main.js"></script>
</body>
</html>
new Vue({
el:"#payFor",
data:{
  books:[
    {
      id:1,
      name:"算法单轮",
      date:"2006-9",
      price:66,
      count:1
    },
    {
      id:2,
      name:"通常讷河",
      date:"2006-10",
      price:67,
      count:1
    },
    {
      id:3,
      name:"立卡DMD",
      date:"2006-1",
      price:61,
      count:1
    },
    {
      id:4,
      name:"撒大声地",
      date:"2006-5",
      price:66,
      count:1
    }
  ]
},
methods:{
  // getPrice(price){
  // return "$"+price.toFixed(2)
  // },
  increme(index){
    this.books[index].count++
  return this.count
  },
  decreme(index){
    if(this.books[index].count>1){
      this.books[index].count--
    }
  return this.count
  },
  removeHandle(index){
    this.books.splice(index,1);
  }
},
filters:{
  showPrice(price){
    return "$"+price.toFixed(2) //过滤器
  }
},
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循环
    //let totalPrice=0
  //   for(let i in this.books){
  //     totalPrice +=this.books[i].price*this.books[i].count
  //   }
  //   return totalPrice
  // }
  //更高级的
  let totalPrice=0
  for(let items of this.books){
    totalPrice+=items.price*items.count
  }
  return totalPrice 
}
}
})

css

 table{ border: 1px solid #e9e9e9; border-spacing: 0; border-collapse: collapse; } th,td{ padding: 8px 16px; border: 1px solid #e9e9e9; } th{ background: #f7f7f7; color: #5c6b77; font-weight: 600; } 

效果图

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!