圖書購物車

顯示圖書購物車界面,移除所有書籍之后,顯示購物車為空


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>v-bind</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
  <style>
    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: #f7f7f7;
      color: #5c6b77;
      font-weight: 600;
    }
  </style>
</head>

<!--需求描述:圖書購物車-->
<body>
<div id= 'vue' >
  <div v-if="books.length>0">
  <table>
    <thead>
    <tr>
      <th></th>
      <th>書籍名稱</th>
      <th>出版日期</th>
      <th>價格</th>
      <th>購買數(shù)量</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(item,index) in books"  :key="item.id">
      <th>{{item.id}}</th>
      <th>{{item.name}}</th>
      <th>{{item.date}}</th>
<!--      <th>{{getFinalPrice(item.price)}}</th>-->
      <th>{{item.price | showPrice}}</th>
      <th>
        <button @click="sub(index)" :disabled="item.count<=1">-</button>
        {{item.count}}
        <button @click="add(index)">+</button>
      </th>
      <th>
        <button @click="remove(index)">移除</button>
      </th>
    </tr>
    </tbody>
  </table>
    <h4>總價:{{totalPrice | showPrice}}</h4>
  </div>
  <h3 v-else>購物車為空</h3>

</div>
<script>
  let vm = new Vue({
    el: '#vue',
    data:{
      books: [
        {
          id: 1,
          name: '算法導(dǎo)論',
          date: '2006 - 9',
          price: 85.00,
          count: 1,
        },
        {
          id: 2,
          name: 'UNIX編程藝術(shù)',
          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,
        }
      ],
      sum: 0
    },
    methods:{
      getFinalPrice(price){
        return '¥  '+ price.toFixed(2)
      },
      add(index){
        this.books[index].count++
      },
      sub(index){
        this.books[index].count--
      },
      remove(index){
        this.books.splice(index,1),
        console.log('移除了第' + index + '個元素')
      }
      },
    computed:{
      totalPrice(){
        let sum = 0
        for(let i=0;i<this.books.length;i++){
          sum += this.books[i].price * this.books[i].count
        }
        return sum
      }
    },
    filters:{
      showPrice(price){
        return '¥  '+ price.toFixed(2)
      }
    }
  })
</script>
</body>
</html>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容