简单的购物车 vue实现

一. 效果图如下:

简单的购物车 vue实现_第1张图片

二. 组件层级结构

简单的购物车 vue实现_第2张图片

三. 局部解析
  1. 计数功能

使用父子级之间传递数据,
父级向子级传值是使用属性传递的,子级用props属性接受父级传过来的值;
子级向父级传值是通过事件传递的,子级定义一个按扭,为按钮添加事件,当点击按钮时,触发父级的自定义事件,并把值传给父级

 
sub(index){
     if(this.productLists[index].count>0){
        this.productLists[index].count--;
     }
    },
    add(index){
      this.productLists[index].count++;
    },
  1. 删除功能

通过splice方法来删除数据

 delDate(index){
     this.productLists.splice(index,1);
   }
  1. 总价计算

使用computed属性来计算总价

 computed:{
    totalPrice(){
      let total=0;
      this.productLists.map(list=>{
        total+=list.price*list.count;
      })
      return total.toFixed(2);//保留两位小数
    }
  }
四. 整体代码:
  • Counter.vue组件


  • Deleter.vue组件


  • App.vue组件



你可能感兴趣的:(vue)