> For the complete documentation index, see [llms.txt](https://zpliu.gitbook.io/booknote/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zpliu.gitbook.io/booknote/vue/an-li-cao-zuo/01-gou-wu-che-jia-ge.md).

# 实现购物车功能

* 当点击商品时，购物车内商品价格相加

```javascript
//HTML部分
    <div class="container">
        <ul>
            <li v-for="item in goods" v-on:click="addPrice(item)">{{item.price}}</li>
        </ul>
        <p>{{totalPrice}}</p>
    </div>


//Vue对象
var app=new Vue({
                el: ".container",
        data:{
            firstname:"111",
            goods:[
            {
                price:10
            },{
                price:20
            }],
            totalPrice:0
        },
        methods:{
            addPrice:function(item){
                this.totalPrice+=item.price
            }
        }
    })
```

* 调整多个商品数目实现总价格变动

  ```markup
      <div class="container">
          <ul>
              <li v-for="item in goods" v-on:click="addPrice()">{{item.price}} <button v-on:click="item.count = item.count -1 < 0 ? 0 : item.count-1">-</button>{{item.count}}<button v-on:click="item.count = item.count+1">+</button></li>
          </ul>
          <p>{{totalPrice}}</p>
      </div>
  ```

  * 在商品栏有增加或删除商品的按钮，使用点击事件，对商品数目进行修改
  * 由于涉及到多个商品使用v-for进行操作
  * li上绑定一个点击事件，处理总价格

  ```javascript
  var app=new Vue({
                  el: ".container",
          data:{
              firstname:"111",
              goods:[
              {
                  price:10,
                  count:0
              },{
                  price:20,
                  count:0
              }],
              totalPrice:0
          },
          methods:{
              addPrice:function(){
                  this.totalPrice=0
                  for(let item of this.goods){
                      this.totalPrice+=item.price*item.count
                  }

              }
              //ES6 写法推荐
           /* addPrice(){
                  this.totalPrice=0
                  for(let item of this.goods){
                      this.totalPrice+=item.price*item.count
                  }

              }*/
          }
      })
  ```

  * 总价格的处理，当每次点击商品时，先将总价格清0再遍历之后将所有的价格相加
  * ES6中简化了methods中函数的写法
