vue实现一个简单的购物车功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yilanyoumeng3/article/details/82022765

今天做了一个简单的购物车功能,主要用了计算属性,指令等知识点,代码如下:

<template>
<div>
    <div  id="cart" v-cloak>
        <template v-if="itemlis.length">
          <table>
              <thead>
                  <tr>
                      <th></th>
                      <th>商品名称</th>
                      <th>商品单价</th>
                      <th>购买数量</th>
                      <th>操作</th>
                  </tr>
              </thead>
              <tbody>
                  <tr v-for=" (item,index) in itemlis" :key="index">
                    <td>{{index+1}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                    <td>
                        <button
                            @click="handleReduce(index)"
                            :disabled="item.count ===1">-</button>
                        {{item.count}}
                        <button @click="handleAdd(index)">+</button>

                    </td>
                    <td>
                        <button @click="handleRemove(index)">移除</button>
                    </td>
                  </tr>
              </tbody>
          </table>
          <div class="total">总价:¥{{totalPrice}}</div>
        </template>
         <div v-else>购物车为空</div>
    </div>
</div>
</template>
<script>
import Vue from 'vue'
import VueResource from 'vue-resource'

Vue.use(VueResource)
export default {
  data () {
    return {
      itemlis: []
    }
  },
  computed: {
//计算并获取总价
    totalPrice () {
      let total = 0
      for (let i = 0; i < this.itemlis.length; i++) {
        let item = this.itemlis[i]
        total += item.price * item.count
      }
      return total.toString().replace(/\B(?=(\d{3})+$)/g, ',')
    }
  },
  methods: {

  //获取商品列表
    getGoodList () {
      this.$http.get('api/goodlist').then(
        res => {
          var arrJson = JSON.parse(res.bodyText)
          this.itemlis = arrJson.data.list
        },
        function (err) {
          console.log(err)
        }
      )
    },
    //减少商品数量
    handleReduce (index) {
      if (this.itemlis[index].count === 1) return
      this.itemlis[index].count--
    },
     //增加商品数量
    handleAdd (index) {
      this.itemlis[index].count++
    },
    //从购物车中移除该商品
    handleRemove (index) {
      this.itemlis.splice(index, 1)
    }
  },
  mounted () {
  //获取商品
    this.getGoodList()
  }
}
</script>

<style scoped>
.total{
    text-align: left ;
}
[v-cloak]{
    display: none;
}
table{
    border: 1px solid #e9e9e9;
    border-collapse: collapse;
    border-spacing: 0;
    empty-cells: show;
}
th,td{
    padding: 8px 16px;
    border:1px solid #e9e9e9;
    text-align: left }
th{
    background: #f7f7f7;
    color: #5c6b77;
    font-weight: 600;
    white-space: nowrap;
}
</style>

猜你喜欢

转载自blog.csdn.net/yilanyoumeng3/article/details/82022765