Vue-购物车简单案例

简介: Vue-购物车简单案例

效果图:

代码部分:

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;
}


目录
相关文章
|
2天前
|
JavaScript
vue的生命周期
vue的生命周期
10 3
|
2天前
|
JavaScript 前端开发
vue的生命周期
vue的生命周期
11 2
|
1天前
|
缓存 JavaScript
什么是vue的计算属性?为什么使用?怎么使用?举例说明
什么是vue的计算属性?为什么使用?怎么使用?举例说明
|
1天前
|
缓存 JavaScript 前端开发
Vue基础
Vue基础
13 2
|
2天前
|
JavaScript 前端开发 API
什么是vue
什么是vue
11 4
|
2天前
|
JavaScript API 开发者
Vue中双向数据绑定是如何实现的?底层原理简介
Vue中双向数据绑定是如何实现的?底层原理简介
9 4
|
2天前
|
JavaScript 安全 前端开发
vue怎么处理跨域,原理?
vue怎么处理跨域,原理?
14 2
|
2天前
|
资源调度 JavaScript
vue的跳转传参
vue的跳转传参
8 0
|
2天前
|
缓存 JavaScript 开发者
什么是vue的计算属性
什么是vue的计算属性
7 0
|
2天前
|
JavaScript
vue组件中data为什么必须是一个函数?
vue组件中data为什么必须是一个函数?
7 1