vuejs手把手教你写一个完整的购物车实例代码

由于我们公司是主营业务是海淘,所以每个项目都是类似淘宝天猫之类的商城,那么购物车就是一个重点开发功能模块。介于之前我都是用jq来写购物车的,这次就用vuejs来写一个购物车。下面我就从全选,数量控制器,运费,商品金额计算等方法来演示一下一个能用在实际场景的购物车是怎么做出来的以及记录一下这次用vuejs踩过的坑。

1.一层数据结构-全选

下面这段代码和vuejs官网里面checkbox绑定很像。不明白的可以直接上vuejs官网看看。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuejs-全选</title>
<style type="text/css">
* {
  padding: 0;
  margin: 0;
}
a {
  color: #333;
  text-decoration:none;
}
</style>
</head>
<body>
<label>
  <input type="checkbox" name="all" v-on:click="chooseAll" v-model="selectArr.length==goodsList.length" />
  <span>全选</span>
</label>
<div v-for="(index, item) in goodsList">
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
    <input type="checkbox" :value="index" v-model="selectArr" />
    商品名称:<span v-html="item.name"></span> |
    价格:<span v-html="item.price"></span>
  </a>
</div>
<label>
  <input type="checkbox" name="all" v-on:click="chooseAll" v-model="selectArr.length==goodsList.length" />
  <span>全选</span>
</label>
<script src="http://cdn.bootcss.com/vue/1.0.7/vue.js"></script>
<script>
var vue = new Vue({
  el : 'body',
  data : {
    goodsList : [
      {
        name : '山本汉方1',
        price : '19.00'
      },
      {
        name : '山本汉方2',
        price : '19.00'
      },
      {
        name : '山本汉方3',
        price : '19.00'
      },
      {
        name : '山本汉方4',
        price : '19.00'
      },
      {
        name : '山本汉方5',
        price : '19.00'
      },
    ],
    selectArr : []
  },
  ready : function() {},
  methods : {
    chooseAll : function(event) {
      var oThis = this;
      oThis.selectArr = [];
      if ( event.currentTarget.checked ) {
        oThis.goodsList.forEach(function(item , index) {
          oThis.selectArr.push(index);
        });
      }
      console.log(oThis.selectArr);
    }
  }
})
</script>
</body>
</html>

2.二层数据结构-全选

一层数据结构的购物车在现实中是很少看到的,比如我们最熟悉的淘宝购物车是按照店铺分的,那么必然是多层的数据结构。这次在写这个二层数据接口的全选,碰到一个很大的坑,一开始我是用了一层数据结构的数据,发现当对象数组里面的某个值改变了,视图竟然没有触发!,所以会造成下面所有的checkbox都被选中了,最上面的那个全选checkbox竟然还是没有被选中。感觉告诉我这是vuejs的坑,后来发现是js的坑。具体可以看这个。方法是百度到了,可是放我这里没有用(应该是版本问题)。于是我就改了数据结构。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuejs-全选</title>
<style type="text/css">
* {
  padding: 0;
  margin: 0;
}
a {
  color: #333;
  text-decoration:none;
}
.goods-item {
  display: block;
}
.store-item {
  margin-bottom: 20px;
}
</style>
</head>
<body>
<div v-for="(index1, item) in goodsObj" class="store-item">
  <p>
    <span v-html="item.name"></span>
    <label>
      <input type="checkbox" name="all" v-on:click="chooseShopGoods(index1)" v-model="item.checked" />
      <span>全选</span>
    </label>
  </p>
  <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" v-for="(index, data) in item.list" class="goods-item">
    <input type="checkbox" v-model="data.checked" v-on:click="choose(index1, index)" />
    商品名称:<span v-html="data.name"></span> |
    价格:<span v-html="data.price"></span>
  </a>
</div>
<label>
  <input type="checkbox" name="all" v-on:click="chooseAllGoods()" v-model="allChecked" />
  <span>全选</span>
</label>
<script src="http://cdn.bootcss.com/vue/1.0.7/vue.js"></script>
<script>
var goodsObj = [
  {
    name : '大胖的店',
    checked : false,
    list : [
      {
        name : '麻辣二胖',
        price : 23.00,
        realStock : 10,
        fare : 1.5,
        num : 1,
        checked : false,
      },

      {
        name : '香辣二胖',
        price : 21.00,
        realStock : 2,
        fare : 1.5,
        num : 2,
        checked : false,
      },

      {
        name : '红烧二胖',
        price : 88.00,
        realStock : 8,
        fare : 1.5,
        num : 4,
        checked : false,
      }
    ]
  },

  {
    name : '二胖的店',
    checked : false,
    list : [
      {
        name : '漂亮的裙子',
        price : 166.00,
        realStock : 10,
        fare : 2,
        num : 1,
        checked : false,
      },

      {
        name : '漂亮的短袖',
        price : 188.00,
        realStock : 2,
        fare : 1.5,
        num : 2,
        checked : false,
      },

      {
        name : '漂亮的鞋子',
        price : 299.00,
        realStock : 1,
        fare : 3,
        num : 1,
        checked : false,
      }
    ]
  },

  {
    name : '胖胖的店',
    checked : false,
    list : [
      {
        name : '福满多',
        price : 3.00,
        realStock : 10,
        fare : .5,
        num : 10,
        checked : false,
      },

      {
        name : '精品卫龙',
        price : 1.50,
        realStock : 2,
        fare : 2,
        num : 2,
        checked : false,
      },

      {
        name : '周长江',
        price : 2.50,
        realStock : 3,
        fare : 5,
        num : 2,
        checked : false,
      }
    ]
  },
];
var vue = new Vue({
  el : 'body',
  data : {
    goodsObj : goodsObj,
    allChecked : false
  },
  ready : function() {

  },
  methods : {
    // 全部商品全选
    chooseAllGoods : function() {
      var flag = true;
      if ( this.allChecked ) {
        flag = false;
      }
      for ( var i = 0, len = this.goodsObj.length; i < len; i++ ) {
        this.goodsObj[i]['checked'] = flag;
        var list = this.goodsObj[i]['list'];
        for ( var k = 0, len1 = list.length; k < len1; k++ ) {
          list[k]['checked'] = flag;
        }
      }
      this.allChecked = !this.allChecked;
    },

    // 每个店铺全选
    chooseShopGoods : function( index) {
      var list = this.goodsObj[index]['list'],
        len = list.length;
      if ( this.goodsObj[index]['checked'] ) {
        for (var i = 0; i < len; i++ ) {
          list[i]['checked'] = false;
        }
      } else {
        for (var i = 0; i < len; i++ ) {
          list[i]['checked'] = true;
        }
      }
      this.goodsObj[index]['checked'] = !this.goodsObj[index]['checked'];

      // 判断是否选择所有商品的全选
      this.isChooseAll();
    },

    // 单个选择
    choose : function( index1, index) {
      var list = this.goodsObj[index1]['list'],
        len = list.length;
      if ( list[index]['checked'] ) {
        this.goodsObj[index1]['checked'] = false;
        this.allChecked = false;
        list[index]['checked'] = !list[index]['checked'];
      } else {
        list[index]['checked'] = !list[index]['checked'];

        // 判断是否选择当前店铺的全选
        var flag = true;
        for (var i = 0; i < len; i++ ) {
          if ( list[i]['checked'] == false ) {
            flag = false;
            break;
          }
        }
        flag == true ? this.goodsObj[index1]['checked'] = true : this.goodsObj[index1]['checked'] = false;
      }

      // 判断是否选择所有商品的全选
      this.isChooseAll();
    },

    // 判断是否选择所有商品的全选
    isChooseAll : function() {
      var flag1 = true;
      for ( var i = 0, len = this.goodsObj.length; i < len; i++ ) {
        if ( this.goodsObj[i]['checked'] == false ) {
          flag1 = false;
          break;
        }
      }
      flag1 == true ? this.allChecked = true : this.allChecked = false;
    },

  }
})
</script>
</body>
</html>

3.一层数据结构-数量选择器

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuejs-数量选择器(1层数据结构)</title>
<style type="text/css">
*{
  padding:0;
  margin: 0;
  box-sizing: border-box;
  font-size: 16px;
}
.clearfix:after {
  content: ".";
  visibility: hidden;
  display: block;
  height: .1px;
  font-size: .1em;
  line-height: 0;
  clear: both;
}
.quantity-selector {
  margin-bottom: 20px;
  width: 8.571rem;
  line-height: 2.857rem;
  border: 1px solid #d1d6e4;
  border-radius: 3px;
}
.quantity-selector .reduce,
.quantity-selector .add {
  float: left;
  width: 33.33%;
  border-right: 1px solid #d1d6e4;
  text-align: center;
  cursor: pointer;
}
.quantity-selector .number {
  float: left;
  width: 33.33%;
  height: 2.857rem;
  padding: .5rem 0;
  line-height: 1rem;
  border: none;
  text-align: center;
}
.quantity-selector .add {
  border-left: 1px solid #d1d6e4;
  border-right: none;
}
.quantity-selector .disable {
  color: #d2d2d2;
  cursor: default;
}
</style>
</head>
<body>

<div v-for="data in goodsList">
  <p>商品数量 :<span v-html="data.num"></span></p>
  <p>商品库存 :<span v-html="data.realStock"></span></p>
  <div class="quantity-selector clearfix">
    <span class="reduce" v-on:click="numChange($index, -1)" v-bind:class="{ 'disable' : data.num==1 }">-</span>
    <input type="number" v-bind:value="data.num" class="number" v-bind:data-realStock="data.realStock" v-on:keyUp="numEntry($index)" v-on:keyDown="numEntry($index)" v-model="data.num"/>
    <span class="add" v-on:click="numChange($index, 1)" v-bind:class="{ 'disable' : data.num==data.realStock }">+</span>
  </div>
</div>

<script src="http://cdn.bootcss.com/vue/1.0.7/vue.js"></script>
<script>
var vue = new Vue({
  el : 'body',
  data : {
    goodsList : [
      {
        name : '山本汉方1',
        price : '19.00',
        realStock : 10,
        num : 1
      },
      {
        name : '山本汉方1',
        price : '19.00',
        realStock : 7,
        num : 8
      },
      {
        name : '山本汉方1',
        price : '19.00',
        realStock : 2,
        num : 2
      },
    ]
  },
  ready : function() {},
  methods : {
    numChange : function(index, numChange) {
      var goods = this.goodsList[index];
      if ( numChange == 1 ) {
        goods.num++;
      } else if ( numChange == -1 ) {
        goods.num--;
      }

      if ( goods.num <= 1 ) {
        goods.num = 1;
      } 

      if ( goods.num >= goods.realStock ) {
        goods.num = goods.realStock;
      }
    },

    numEntry : function(index) {
      var goods = this.goodsList[index];
      if ( goods.num <=1 ) {
        goods.num = 1;
      }

      if ( goods.num > goods.realStock ) {
        goods.num = goods.realStock;
      }

    }

  }
})
</script>
</body>
</html>

4.二层数据结构-数据选择器

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuejs-数量选择器(2层数据结构)</title>
<style type="text/css">
*{
  padding:0;
  margin: 0;
  box-sizing: border-box;
  font-size: 16px;
}
a {
  text-decoration: none;
  color: #333;
}
.clearfix:after {
  content: ".";
  visibility: hidden;
  display: block;
  height: .1px;
  font-size: .1em;
  line-height: 0;
  clear: both;
}
.quantity-selector {
  margin: 0 auto;
  width: 8.571rem;
  line-height: 30px;
  border: 1px solid #d1d6e4;
  border-radius: 3px;
}
.quantity-selector .reduce,
.quantity-selector .add {
  float: left;
  width: 33.33%;
  border-right: 1px solid #d1d6e4;
  text-align: center;
  cursor: pointer;
}
.quantity-selector .number {
  float: left;
  width: 33.33%;
  height: 30px;
  border: none;
  padding-left: 10px;
  text-align: center;
}
.quantity-selector .add {
  border-left: 1px solid #d1d6e4;
  border-right: none;
}
.quantity-selector .disable {
  color: #d2d2d2;
  cursor: default;
}

/*店铺开始*/
.store-item {
  width: 600px;
  margin: 30px auto;
}
.store-item th {
  height: 40px;
  background: #d2d2d2;
  -webkit-text-stroke: 1px #ff7500;
  font-size: 18px;
}
.store-item td {
  height: 60px;
  text-align: center;
}
.cal-store-box {
  text-align: right;
}
.store-footer {
  width: 600px;
  margin: 50px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/*店铺结束*/
</style>
</head>
<body>
<div class="store-item" v-for="(index1, item) in goodsObj">
  <p v-html="index1"></p>
  <table class="store-item">
    <col width="10%"></col>
    <col width="10%"></col>
    <col width="20%"></col>
    <col width="10%"></col>
    <col width="40%"></col>
    <col width="10%"></col>
    <thead class="thead">
      <tr>
        <th>选择</th>
        <th>商品</th>
        <th>单价</th>
        <th>运费</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(index, data) in item">
        <td>

        </td>
        <td>
          <p><span v-html="data.name"></span></p>
        </td>
        <td v-html="(data.price).toFixed(2)"></td>
        <td v-html="(data.fare).toFixed(2)"></td>
        <td>
          <div class="quantity-selector clearfix">
            <span class="reduce" v-on:click="numChange(index1, $index, -1)" v-bind:class="{ 'disable' : data.num==1 }">-</span>
            <input type="number" v-bind:value="data.num" class="number" v-bind:data-realStock="data.realStock" v-on:keyUp="numEntry(index1, $index)" v-on:keyDown="numEntry(index1, $index)" v-model="data.num"/>
            <span class="add" v-on:click="numChange(index1, $index, 1)" v-bind:class="{ 'disable' : data.num==data.realStock }">+</span>
          </div>
        </td>
        <td>
          <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >删除</a>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="cal-store-box">
    <p>店铺总运费: <span v-html="calEveryFare(index1)"></span></p>
    <p>店铺商品总金额: <span v-html="calEveryStore(index1)"></span></p>
  </div>
</div>

<div class="store-footer">
  <!-- <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
    <input type="checkbox" />
    <span>全选</span>
  </a> -->
  <div class="cal-box">
    <p>商品总金额:<span v-html="totalFare"></span></p>
    <p>运费总金额:<span v-html="totalMoney"></span></p>
  </div>
</div>

<script src="http://cdn.bootcss.com/vue/1.0.7/vue.js"></script>
<script>
var goodsObj = {
  '大胖的店' : [
    {
      name : '康师傅',
      price : 23.00,
      realStock : 10,
      fare : 1.5,
      num : 1
    },

    {
      name : '今麦郎',
      price : 26.00,
      realStock : 2,
      fare : 1.5,
      num : 2
    },

    {
      name : '比巴卜',
      price : 88.00,
      realStock : 8,
      fare : 1.5,
      num : 4
    }
  ],

  '二胖的店' : [
    {
      name : '好看的鞋子',
      price : 23.00,
      realStock : 7,
      fare : 2,
      num : 1
    },

    {
      name : '好看的裙子',
      price : 26.00,
      realStock : 5,
      fare : 2,
      num : 5
    },

    {
      name : '好看的短袖',
      price : 88.00,
      realStock : 10,
      fare : 2,
      num : 1
    }
  ],

  '胖胖的店' : [
    {
      name : '福满多1号',
      price : 26.00,
      realStock : 7,
      fare : 3,
      num : 1
    },

    {
      name : '福满多2号',
      price : 26.00,
      realStock : 7,
      fare : 3,
      num : 1
    },

    {
      name : '经典卫龙辣条',
      price : 16.00,
      realStock : 50,
      fare : 3,
      num : 5
    },

    {
      name : '霸王牛津',
      price : 80.00,
      realStock : 10,
      fare : 3,
      num : 6
    }
  ]
};
var vue = new Vue({
  el : 'body',
  data : {
    goodsObj : goodsObj,
    totalMoney : 0,
    totalFare : 0
  },
  ready : function() {
    this.calTotalMoney();
    this.calTotalFare();
  },
  methods : {
    numChange : function(index1, index, numChange) {
      var goods = this.goodsObj[index1][index],
        oThis = this;
      if ( numChange == 1 ) {
        goods.num++;
      } else if ( numChange == -1 ) {
        goods.num--;
      }

      if ( goods.num <= 1 ) {
        goods.num = 1;
      } 

      if ( goods.num >= goods.realStock ) {
        goods.num = goods.realStock;
      }
      this.calTotalMoney();
    },

    numEntry : function(index1, index) {
      var goods = this.goodsObj[index1][index];
      if ( goods.num <=1 ) {
        goods.num = 1;
      }

      if ( goods.num > goods.realStock ) {
        goods.num = goods.realStock;
      }
      this.calTotalMoney();
    },

    calEveryStore : function(index) {
      var everyStoreMoney = 0;
      this.goodsObj[index].forEach(function(item, index, arr) {
        everyStoreMoney += parseFloat(item.price) * parseFloat(item.num);
      });
      return everyStoreMoney.toFixed(2);
    },

    calEveryFare : function(index) {
      var everyStoreFare = 0;
      this.goodsObj[index].forEach(function(item, index, arr) {
        everyStoreFare += parseFloat(item.fare) * parseFloat(item.num);
      });
      return everyStoreFare.toFixed(2);
    },

    calTotalMoney : function () {
      var oThis = this;
      this.totalMoney = 0;
      for ( var x in this.goodsObj ) {
        this.goodsObj[x].forEach(function(item, index, arr) {
          oThis.totalMoney += parseFloat(item.price) * parseFloat(item.num);
        });
      }
      this.totalMoney = this.totalMoney.toFixed(2);
    },

    calTotalFare : function () {
      var oThis = this;
      this.totalFare = 0;
      for ( var x in this.goodsObj ) {
        this.goodsObj[x].forEach(function(item, index, arr) {
          oThis.totalFare += parseFloat(item.fare) * parseFloat(item.num);
        });
      }
      this.totalFare = this.totalFare.toFixed(2);
    },

  }
})
</script>
</body>
</html>

5.一个完整的购物车

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>vuejs-数量选择器(2层数据结构)</title>
<style type="text/css">
*{
  padding:0;
  margin: 0;
  box-sizing: border-box;
  font-size: 16px;
}
a {
  text-decoration: none;
  color: #333;
}
.clearfix:after {
  content: ".";
  visibility: hidden;
  display: block;
  height: .1px;
  font-size: .1em;
  line-height: 0;
  clear: both;
}
.quantity-selector {
  margin: 0 auto;
  width: 8.571rem;
  line-height: 30px;
  border: 1px solid #d1d6e4;
  border-radius: 3px;
}
.quantity-selector .reduce,
.quantity-selector .add {
  float: left;
  width: 33.33%;
  border-right: 1px solid #d1d6e4;
  text-align: center;
  cursor: pointer;
}
.quantity-selector .number {
  float: left;
  width: 33.33%;
  height: 30px;
  border: none;
  padding-left: 10px;
  text-align: center;
}
.quantity-selector .add {
  border-left: 1px solid #d1d6e4;
  border-right: none;
}
.quantity-selector .disable {
  color: #d2d2d2;
  cursor: default;
}

label {
  cursor: pointer;
}

.choose-all {
  margin-left: 20px;
}

/*店铺开始*/
.store-item {
  width: 600px;
  margin: 30px auto;
}
.store-item th {
  height: 40px;
  background: #d2d2d2;
  -webkit-text-stroke: 1px #ff7500;
  font-size: 18px;
}
.store-item td {
  height: 60px;
  text-align: center;
}
.cal-store-box {
  text-align: right;
}
.store-footer {
  width: 600px;
  margin: 50px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/*店铺结束*/
</style>
</head>
<body>
<div class="store-item" v-for="(index1, item) in goodsObj">
  <p>
    <span v-html="item.name"></span>
    <label class="choose-all">
      <input type="checkbox" name="all" v-on:click="chooseShopGoods(index1)" v-model="item.checked" />
      <span>全选</span>
    </label>
  </p>
  <table class="store-item">
    <col width="10%"></col>
    <col width="15%"></col>
    <col width="15%"></col>
    <col width="10%"></col>
    <col width="40%"></col>
    <col width="10%"></col>
    <thead class="thead">
      <tr>
        <th>选择</th>
        <th>商品</th>
        <th>单价</th>
        <th>运费</th>
        <th>数量</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="(index, data) in item.list">
        <td>
          <input type="checkbox" name="all" v-model="data.checked" v-on:click="choose(index1, index)" />
        </td>
        <td>
          <p><span v-html="data.name"></span></p>
        </td>
        <td v-html="(data.price).toFixed(2)"></td>
        <td v-html="(data.fare).toFixed(2)"></td>
        <td>
          <div class="quantity-selector clearfix">
            <span class="reduce" v-on:click="numChange(index1, $index, -1)" v-bind:class="{ 'disable' : data.num==1 }">-</span>
            <input type="number" v-bind:value="data.num" class="number" v-bind:data-realStock="data.realStock" v-on:keyUp="numEntry(index1, $index)" v-on:keyDown="numEntry(index1, $index)" v-model="data.num"/>
            <span class="add" v-on:click="numChange(index1, $index, 1)" v-bind:class="{ 'disable' : data.num==data.realStock }">+</span>
          </div>
        </td>
        <td>
          <a href="javascript:;" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" v-on:click="delGoods(index1, index)">删除</a>
        </td>
      </tr>
    </tbody>
  </table>
  <div class="cal-store-box">
    <p>店铺总运费: <span v-html="calEveryFare(index1)"></span></p>
    <p>店铺商品总金额: <span v-html="calEveryStore(index1)"></span></p>
  </div>
</div>

<div class="store-footer">
  <label>
    <input type="checkbox" v-on:click="chooseAllGoods($event)" v-model="allChecked" />
    <span>全选</span>
  </label>
  <div class="cal-box">
    <p>商品总运费:<span v-html="totalFare.toFixed(2)"></span></p>
    <p>商品总金额:<span v-html="totalMoney.toFixed(2)"></span></p>
  </div>
</div>

<script src="http://cdn.bootcss.com/vue/1.0.7/vue.js"></script>
<script>
var goodsObj = [
  {
    name : '大胖的店',
    checked : false,
    list : [
      {
        name : '麻辣二胖',
        price : 23.00,
        realStock : 10,
        fare : 1.5,
        num : 1,
        checked : false,
      },

      {
        name : '香辣二胖',
        price : 21.00,
        realStock : 2,
        fare : 1.5,
        num : 2,
        checked : false,
      },

      {
        name : '红烧二胖',
        price : 88.00,
        realStock : 8,
        fare : 1.5,
        num : 4,
        checked : false,
      }
    ]
  },

  {
    name : '二胖的店',
    checked : false,
    list : [
      {
        name : '漂亮的裙子',
        price : 166.00,
        realStock : 10,
        fare : 2,
        num : 1,
        checked : false,
      },

      {
        name : '漂亮的短袖',
        price : 188.00,
        realStock : 2,
        fare : 1.5,
        num : 2,
        checked : false,
      },

      {
        name : '漂亮的鞋子',
        price : 299.00,
        realStock : 1,
        fare : 3,
        num : 1,
        checked : false,
      }
    ]
  },

  {
    name : '胖胖的店',
    checked : false,
    list : [
      {
        name : '福满多',
        price : 3.00,
        realStock : 10,
        fare : .5,
        num : 10,
        checked : false,
      },

      {
        name : '精品卫龙',
        price : 1.50,
        realStock : 2,
        fare : 2,
        num : 2,
        checked : false,
      },

      {
        name : '周长江',
        price : 2.50,
        realStock : 3,
        fare : 5,
        num : 2,
        checked : false,
      }
    ]
  },
];
var vue = new Vue({
  el : 'body',
  data : {
    goodsObj : goodsObj,
    totalMoney : 0,
    totalFare : 0,
    allChecked : false
  },
  ready : function() {},
  methods : {

    // 全部商品全选
    chooseAllGoods : function() {
      var flag = true;
      if ( this.allChecked ) {
        flag = false;
      }
      for ( var i = 0, len = this.goodsObj.length; i < len; i++ ) {
        this.goodsObj[i]['checked'] = flag;
        var list = this.goodsObj[i]['list'];
        for ( var k = 0, len1 = list.length; k < len1; k++ ) {
          list[k]['checked'] = flag;
        }
      }
      this.allChecked = !this.allChecked;
      this.calTotalMoney();
      this.calTotalFare();
    },

    // 每个店铺全选
    chooseShopGoods : function( index) {
      var list = this.goodsObj[index]['list'],
        len = list.length;
      if ( this.goodsObj[index]['checked'] ) {
        for (var i = 0; i < len; i++ ) {
          list[i]['checked'] = false;
        }
      } else {
        for (var i = 0; i < len; i++ ) {
          list[i]['checked'] = true;
        }
      }
      this.goodsObj[index]['checked'] = !this.goodsObj[index]['checked'];

      // 判断是否选择所有商品的全选
      this.isChooseAll();

      this.cal(index);
    },

    // 单个选择
    choose : function( index1, index) {
      var list = this.goodsObj[index1]['list'],
        len = list.length;
      if ( list[index]['checked'] ) {
        this.goodsObj[index1]['checked'] = false;
        this.allChecked = false;
        list[index]['checked'] = !list[index]['checked'];
      } else {
        list[index]['checked'] = !list[index]['checked'];

        // 判断是否选择当前店铺的全选
        var flag = true;
        for (var i = 0; i < len; i++ ) {
          if ( list[i]['checked'] == false ) {
            flag = false;
            break;
          }
        }
        flag == true ? this.goodsObj[index1]['checked'] = true : this.goodsObj[index1]['checked'] = false;
      }

      // 判断是否选择所有商品的全选
      this.isChooseAll();

      this.cal(index);
    },

    // 判断是否选择所有商品的全选
    isChooseAll : function() {
      var flag1 = true;
      for ( var i = 0, len = this.goodsObj.length; i < len; i++ ) {
        if ( this.goodsObj[i]['checked'] == false ) {
          flag1 = false;
          break;
        }
      }
      flag1 == true ? this.allChecked = true : this.allChecked = false;
    },

    // 商品数量控制
    numChange : function(index1, index, numChange) {
      var goods = this.goodsObj[index1]['list'][index],
        oThis = this;
      if ( numChange == 1 ) {
        goods.num++;
      } else if ( numChange == -1 ) {
        goods.num--;
      }

      if ( goods.num <= 1 ) {
        goods.num = 1;
      } 

      if ( goods.num >= goods.realStock ) {
        goods.num = goods.realStock;
      }

      this.cal(index);
    },

    // 用户填写容错处理
    numEntry : function(index1, index) {
      var goods = this.goodsObj[index1]['list'][index];
      if ( goods.num <=1 ) {
        goods.num = 1;
      }

      if ( goods.num > goods.realStock ) {
        goods.num = goods.realStock;
      }
      this.cal(index);
    },

    // 计算每个店铺的商品总额
    calEveryStore : function(index) {
      var everyStoreMoney = 0,
        list = this.goodsObj[index]['list'];
      list.forEach(function(item, index, arr) {
        if ( list[index]['checked'] ) {
          everyStoreMoney += parseFloat(item.price) * parseFloat(item.num);
        }
      });
      return everyStoreMoney.toFixed(2);
    },

    // 计算每个店铺的运费总额
    calEveryFare : function(index) {
      var everyStoreFare = 0,
        list = this.goodsObj[index]['list'];
      list.forEach(function(item, index, arr) {
        if ( list[index]['checked'] ) {
          everyStoreFare += parseFloat(item.fare) * parseFloat(item.num);
        }
      });
      return everyStoreFare.toFixed(2);
    },

    // 计算商品总金额
    calTotalMoney : function () {
      var oThis = this;
      this.totalMoney = 0;
      for ( var i = 0, len = this.goodsObj.length; i < len; i++ ) {
        var list = this.goodsObj[i]['list'];
        list.forEach(function(item, index, arr) {
          if ( list[index]['checked'] ) {
            oThis.totalMoney += parseFloat(item.price) * parseFloat(item.num);
          }
        });
      }
    },

    // 计算商品总运费
    calTotalFare : function () {
      var oThis = this;
      this.totalFare = 0;
      for ( var i = 0, len = this.goodsObj.length; i < len; i++ ) {
        var list = this.goodsObj[i]['list'];
        list.forEach(function(item, index, arr) {
          if ( list[index]['checked'] ) {
            oThis.totalFare += parseFloat(item.fare) * parseFloat(item.num);
          }
        });
      }
    },

    // 计算方法集合
    cal : function(index) {
      this.calEveryStore(index);
      this.calEveryFare(index);
      this.calTotalMoney();
      this.calTotalFare();
    },

    // 删除操作
    delGoods : function(index1, index) {
      console.log(index1);
      console.log(index);
      this.goodsObj[index1]['list'].splice(index, 1);
      this.cal(index);
    }

  }
})
</script>
</body>
</html>

效果如下:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

时间: 2017-07-04

用vue和node写的简易购物车实现

项目介绍 这是用vue写前端,用node来接收前端发来的请求,然后进行相应的数据操作,例如数据的存取和删除等.这是个人的练习项目,目前功能做的比较简单,主要是展示商品列表,把商品加入购物车,从购物车删除商品三个小功能. 搭建本地环境 因为是用vue,需要用babel把es6语法转为es5语法. 1.配置.babelrc文件 { "presets": [ "es2015", "stage-2" ], "plugins": [&q

Vue2.0实现购物车功能

简介 vue.js是由华人尤雨溪开发的一套MVVM框架.vue.js 的核心是一个允许你采用简洁的模板语法来声明式的将数据渲染进 DOM 的系统,它非常适用于具有复杂交互逻辑的前端应用,如一些单页应用程序,有很多表单操作,页面中的内容需要根据用户的操作动态变化. 主要特性: 1.响应式的数据绑定  2.组件化开发  3.Virtual DOM 开发准备 工具 我使用的编辑器是sublime text3,首先要先安装个插件sublimeServer,用来搭建一个http服务器,使用详情请查看这篇博

基于Vuejs实现购物车功能

本文实例为大家分享了Vuejs购物车实现代码,供大家参考,具体内容如下 html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>我的vue购物车</title> <link rel="stylesheet" href="css/bootstrap.min.css&q

Vue实现购物车功能

效果图: 代码如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.0.2/css/bootstrap.min.css" rel="external nofollow" /> &l

Vuejs实现购物车功能

开始更新前端框架Vue.JS的相关博客. 功能概述 学习了Vue.JS的一些基础知识,现在利用指令.数据绑定这些基础知识开发一个简单的购物车功能.功能要点如下: (1)展示商品的名称.单价和数量: (2)商品的数量可以增加和减少: (3)购物车的总价要实时更新,即数量发生变动,总价也要相应的改变: (4)商品可以从购物车中移除: (5)具有选择功能,只计算选中的商品的总价. 上一张截图,如下: 代码 代码分成三部分,分别是HTML.JS.CSS.关键的是HTML和JS. HTML <!DOCTY

Javascript实现购物车功能的详细代码

我们肯定都很熟悉商品购物车这一功能,每当我们在某宝某东上购买商品的时候,看中了哪件商品,就会加入购物车中,最后结算.购物车这一功能,方便消费者对商品进行管理,可以添加商品,删除商品,选中购物车中的某一项或几项商品,最后商品总价也会随着消费者的操作随着变化. 现在,笔者对购物车进行了简单实现,能够实现真实购物车当中的大部分功能.在本示例当中,用到了javascript中BOM操作,DOM操作,表格操作,cookie,json等知识点,同时,采用三层架构方式对购物车进行设计,对javascript的

angular.js实现购物车功能

本文实例为大家分享了angular.js购物车功能的具体代码,供大家参考,具体内容如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>购物车</title> <script src="angularjs/angular.js"></script> <st

使用Angular.js实现简单的购物车功能

先给大家分享实现代码,在代码下面有效果图展示,大家可以两者结合参考下,废话不多说了,具体代码如下所示: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="http://code.angularjs.org/1.2.5/angular.min.js"></script

Android实现二级列表购物车功能

本文实例为大家分享了Android实现二级列表购物车功能的具体代码,供大家参考,具体内容如下 MainActivity: package com.baway.twoshopcar; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckBox; import android.widget.Expa

Android实现简单购物车功能

本文实例为大家分享了Android实现购物车功能的具体代码,供大家参考,具体内容如下 MainActivity布局: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"

angularjs实现简单的购物车功能

本文实例为大家分享了angularjs实现购物车功能的具体代码,供大家参考,具体内容如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> *{ margin: 0; padding: 0; margin-left: 10px; } li{ list-

JAVAEE中用Session简单实现购物车功能示例代码

Session简单实现购物车功能 这个小程序主要就3个页面,一个商品列表页面(HomeServlet),一个是提示加入购物车页面(AddCartTipServlet),一个是显示购物车清单页面(ShowCartServlet). HomeServlet页面: @WebServlet({ "/HomeServlet", "/home" }) public class HomeServlet extends HttpServlet { private static fi

利用python实现简单的循环购物车功能示例代码

本文主要给大家介绍了关于python实现循环购物车功能的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 示例代码 # -*- coding: utf-8 -*- __author__ = 'hujianli' shopping = [ ("iphone6s", 5000), ("book python", 81), ("iwach", 3200), ("电视机", 2200) ] def zero(name):