1. 程式人生 > >vue實現簡單購物車

vue實現簡單購物車

效果圖如下
比較醜。。。
比較醜哈哈。。
程式碼如下

<template>
<div class="user">
  <div><input type="checkbox" v-model="checkAll" @click="check(checkAll)">全選</div>
  <ul v-for="(item,i) in list" v-bind:key="item.name">
    <li><input type="checkbox" v-model="item.isCheck">
      <span>{{item.name}}</span>
      <span style="margin-left: 100px">
        <button class="el-icon-minus icon" @click="reduce(i)" ></button>
        <input type="text" value="0" v-model="item.num">
        <button class="el-icon-plus icon" @click="add(i)"></button>
      </span>
      <span style="margin-left: 100px">單價{{item.much}}</span>
      <span style="margin-left: 100px">單個總價{{item.num*item.much}}</span>
    </li>
  </ul>
  <div>總價:{{totalPrice}}</div>
    </div>
</template>

<script>
export default {
  data () {
    return {
      checkAll: '',
      list: [
        {name: 'jack', isCheck: false, num: 0, much: 10},
        {name: 'rose', isCheck: false, num: 0, much: 10},
        {name: 'mike', isCheck: false, num: 0, much: 10}
      ]
    }
  },
  computed: {
    totalPrice: function () {
      let _this = this
      let total = 0
      _this.list.forEach(function (item) {
        if (item.isCheck) {
          total += item.num * item.much
        }
      })
      return total
    }

  },
  methods: {
    check (data) {
      let _this = this
      if (!data) {
        _this.list.forEach(function (item) {
          item.isCheck = true
        })
      } else if (data) {
        _this.list.forEach(function (item) {
          item.isCheck = false
        })
      }
    },
    reduce (i) {
      let list = this.list
      let num = list[i].num
      if (!num < 1) {
        num = num - 1
        list[i].num = num
      }
    },
    add (i) {
      let list = this.list
      let num = list[i].num
      num = num + 1
      list[i].num = num
    }
  },
  watch: {
    list: {
      handler (value) {
        let _this = this
        let count = 0
        for (let i = 0; i < value.length; i++) {
          if (value[i].isCheck === true) {
            count++
          }
        }
        if (count === value.length) {
          _this.checkAll = true
        } else {
          _this.checkAll = false
        }
      },
      deep: true
    }
  }

}
</script>

<style>
.red{
  color: red;
}
  .tab{
    height: 60px;
    width: 100%;
    margin: 0 auto;
    background-color: pink;
  }
  .tab div{
    width: 33%;
    border: 1px solid red;
    float: left;
  }
  .el-main{
    line-height: 60px;
  }
  .cur{
    background-color: hotpink;
    color: white;
  }
  li{
    list-style: none;
  }
  .icon{
    cursor: pointer;
  }
</style>