美文网首页
小demo 常用api

小demo 常用api

作者: blank的小粉er | 来源:发表于2019-12-30 12:31 被阅读0次
ES6 find方法及...扩展运算符,添加购物车案列
    //加入购物车
    //var arr1=['a','b','c'];
    //var arr2=[...arr1,'d','e']; //['a','b','c','d','e']
      addCourseToCart(index){
        let item = this.courseList[index];
        //isHasCourse 是否在购物车中存在
        let isHasCourse = this.courseItem.find(x=>x.id == item.id)
        if(isHasCourse){
          isHasCourse.number += 1;
        }else{
          //增加number和isActive属性
          this.courseItem.push({
            ...item,
            number: 1,
            isActive: true
          });
        }
      },

计算属性computed 过滤filter

computed用来监控自己定义的变量,该变量不在data里面声明,直接在computed里面定义,然后就可以在页面上进行双向数据绑定展示出结果或者用作其他处理;
computed比较适合对多个变量或者对象进行处理后返回一个结果值,也就是数多个变量中的某一个值发生了变化则我们监控的这个值也就会发生变化,举例:购物车里面的商品列表和总金额之间的关系,只要商品列表里面的商品数量发生变化,或减少或增多或删除商品,总金额都应该发生变化。这里的这个总金额使用computed属性来进行计算是最好的选择

  //var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]   把小于5的数字过滤出来
 // console.log(numbers.filter(item=>item<5));
    computed: {)
      //被选中的数目
      isActiveCourse(){
        return this.courseItem.filter(item=>item.isActive).length
      },
      //全部数目
      allCourseList(){
        return this.courseItem.length
      },
      //总价
      allPrice(){
        let num = 0;
        this.courseItem.forEach(item => {
          if(item.isActive){
            num += item.price * item.number
          }
        });
        return num;
      }
    },

相关文章

网友评论

      本文标题:小demo 常用api

      本文链接:https://www.haomeiwen.com/subject/olapoctx.html