Vue基础小实例 --简单购物车

本文详细介绍了使用Vue.js实现购物车功能的过程,包括商品数量增减、移除、结算等功能,通过具体代码示例展示了如何操作数组来更新视图,并使用计算属性进行总价计算。

感觉自己有时候学新的东西就会忘记之前学过的。

Vue实现一个购物车,主要实现了增加数量,减少数量,移除数据,结算等功能,完成图如下:

主要说一下思路:

1.使用一个数组作为一个图书信息的一个整合,展示直接for循环展示

2.图书数量的增加可以无限,但是减少到1就停止,去掉减少这个按钮,可以使用v-if

3.移除按钮,直接删除掉数组中的整个对象,按钮,考虑方法methods

4.结算,当前的数组中所有价格和数量的乘积总和,因为是一个数值,所以考虑计算属性computed

首先是HTML,引入vue

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<div id="app">
  <h2>购物车</h2>
  <table v-if="this.books.length != 0">
    <tr v-for="(item,index) in books" :key="index">
      <td>{{item.book_name}}</td>
      <td>¥{{item.book_price}}</td>
      <td>
        <span @click="item.count++">+</span>
         {{item.count}}
        <span @click="item.count--" v-if="item.count > 1">-</span>
      </td>
      <td>
        <button @click="remove(index)">移除</button>
      </td>
    </tr>
  </table>
  <p>结算:{{result}}</p>
</div>

css样式,可不看

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

js

new Vue({
  el: '#app',
  data:{
    books:[
      {
        book_name:'图书1',
        book_price:12,
        count:1
      },
      {
        book_name:'图书2',
        book_price:30,
        count:1
      },
      {
        book_name:'图书3',
        book_price:52,
        count:1
      }
    ]
  },
  computed:{
    result(){
      var result = 0;
      this.books.map(x => result += x.book_price*x.count);
      return result;
    }
  },
  methods:{
    remove:function(index){
      this.books.splice(index,1);
    }
  }
  
})

补充一个有小数点的数字,一般金额都精确到点的后两位。单数

filters:{
    pricePoint(price){
      return price.toFixed(2);
    }
  }

HTML模板
<td>¥{{item.book_price | pricePoint}}</td>
<p>结算:{{result | pricePoint}}</p>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值