Vue-购物车简单案例

效果图:

75

代码部分:

index.html

<div id="app">
  <div v-if="books.length">
    <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>{{item.id}}</td>
        <td>{{item.bookName}}</td>
        <td>{{item.date}}</td>
        <td>{{item.price | showPrice}}</td>
        <td>
          <button @click="decrement(index)" :disabled="item.count<=1">-</button>
          {{item.count}}
          <button @click="increment(index)">+</button>
        </td>
        <td>
          <button @click="removeClick(index)">移除</button>
        </td>
      </tr>
      </tbody>
    </table>
    <h2>总价格:{{getTotalPrice | showPrice}}</h2>
  </div>
  <div v-else>
    <h2>购物车为空</h2>
  </div>
</div>
<script src="../js/vue.js"></script>
<link rel="stylesheet" href="style.css">
<script src="main.js"></script>

main.js

const app = new Vue({
  el: '#app',
  data: {
    books: [
      {
        id: 1,
        bookName: '《算法导论》',
        date: '2006-9',
        price: 85.00,
        count: 1
      }, {
        id: 2,
        bookName: '《UNIX编程艺术》',
        date: '2006-2',
        price: 59.00,
        count: 1
      }, {
        id: 3,
        bookName: '《编程珠玑》',
        date: '2008-10',
        price: 39.00,
        count: 1
      }, {
        id: 4,
        bookName: '《代码大全》',
        date: '2006-3',
        price: 128.00,
        count: 1
      },
    ]
  },
  computed: {
    getTotalPrice() {
      // let result = 0;
      // for(let i = 0;i<this.books.length;i++){
      //   result += this.books[i].count*this.books[i].price
      // }
      // return  result;
      return this.books.reduce((a,b)=>a+b.price*b.count,0)
    }
  },
  methods: {
    // getFinalPrice(price) {
    //   return '¥'+price.toFixed(2)
    // }
    increment(index) {
      this.books[index].count++;
    },
    decrement(index) {
        this.books[index].count--;
    },
    removeClick(index) {
      this.books.splice(index,1)
    }
  },
  filters: {
    showPrice(price) {
      return '¥'+price.toFixed(2)
    }
  }
})

style.css

#app table {
  text-align: center;
  width: 500px;
}
posted @   JamieChyi  阅读(10)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示