Vue.js实现购物车功能

Vue.js实现购物车功能

1.功能实现
以表格的形式将存放在后端的购物信息展示在前端页面,实现步骤如下:
使用axios技术异步读取json文件里的数据,结合Vue.js的v-for指令将信息逐条迭代存放在表格中,在表格中展示“商品名称”、“商品单价”、“商品数量”等信息,并能对商品进行数量的增加、减少,清除此项订单信息的功能,订单总价随着商品数量的增加和减少实时更新。

2.order.json数据如下

      [
       {
         id:1,
         name:'华为Mate40',
         price:7299,
         count:2
       },
       {
         id:2,
         name:'iphone XR',
         price:6199,
         count:1,
       },
       {
         id:3,
         name:'小米10',
         price:3999,
         count:3
       }]

3.前端界面如下

<body>
  <div id ="app" >
   <template v-if="list.length">
    <table border="1px" style="width: 400px;">
      <thead>
        <tr>
          <th>编号</th>
          <th>商品名称</th>
          <th>商品单价</th>
          <th>购买数量</th>
          <th>操作</th>
        </tr>
      </thead>
      <tr v-for="(product,index) in list">
        <td>{{index+1}}</td>
        <td>{{product.name}}</td>
        <td>{{product.price}} </td>
        <td>
          <button @click="subProduct(index)" :disabled="product.count==1">-</button>
          {{product.count}}
          <button @click="addProduct(index)">+</button>
        </td>
        <td><button @click="removePriduct(index)">移除</button></td>
      </tr>
      <tbody>
      </tbody>
    </table>
    <div>总金额:¥{{totalPrice}}</div>
   </template>
 <template v-else>购物车为空 </template>
</div>
</body>

4.js代码如下

 <script>
   //创建Vue实例,得到 ViewModel
   var app = new Vue({
    el: '#app',
/*数据*/
    data: {
     list:[],
},
/*自动加载函数*/
    mounted(){
    //异步读取json文件数据
    axios.get('/json/order.json',{}).then(response(){
     app.list=response.data;
    );
},
/*执行触发函数*/
    methods: {
      //数量减少
      subProduct:function(index){
        this.list[index].count--;
      },
      //数量增加
      addProduct:function(index){
        this.list[index].count++;
      },
      //清除订单
      removePriduct:function(index){
         this.list.splice(index,1);
      }

},
/*动态计算属性*/
    computed: {
    //返回总金额
      totalPrice:function(){
        var total=0;
        for (var i=0;i < this.list.length;i++){
          total+=this.list[i].price*this.list[i].count;
        }
        return total;
      }
},
   });
  </script>

效果图如下:
在这里插入图片描述

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值