首页 > VUE
vue实验购物车功能
来源:TP课堂 时间:2022-12-25 点击:322

效果:

image.png

<template>
  <div>
    <div v-if="datalist.length < 1">您的购物车为空</div>
    <table v-else>
      <caption>
        <h1>购物车</h1>
      </caption>
      <tr>
        <th></th>
        <th>名称</th>
        <th>数量</th>
        <th>价钱</th>
        <th>操作</th>
      </tr>
      <tr v-for="(item, index) in datalist" :key="item.id">
        <td><input type="checkbox" v-model="item.checkbox" /></td>
        <td>{{ item.name }}</td>
        <td>
          <button @click="item.num--" class="num" :disabled="item.num <= 1">
            -</button
          >{{ item.num }}<button @click="item.num++" class="num">+</button>
        </td>
        <td>{{ item.price }}</td>
        <td><a href="#" @click.prevent="del(index)">删除</a></td>
      </tr>
      <tr>
        <td colspan="5" align="right">总价:¥{{ totalPrice.toFixed(2) }}</td>
      </tr>
    </table>
  </div>
</template>
<script>
export default {
  name: 'App',
  data() {
    return {
      datalist: [
        { id: 1, checkbox: true, name: '《曾国藩的启示》', price: 58, num: 1 },
        { id: 2, checkbox: true, name: '北京', price: 45, num: 1 },
        { id: 3, checkbox: true, name: '天津', price: 28, num: 1 },
        { id: 4, checkbox: true, name: '深圳', price: 100, num: 1 }
      ]
    }
  },
  computed: {
    totalPrice: {
      get() {
        let sum = 0
        for (const book of this.datalist) {
          if (book.checkbox === true) {
            sum += book.price * book.num
          }
        }
        return sum
      }
    }
  },
  methods: {
    del(index) {
      this.datalist.splice(index, 1)
    }
  }
}
</script>
<style lang="scss">
table {
  border-collapse: collapse;
  border-spacing: 0;
}
th {
  background: #ddd;
  border: 1px solid #ddd;
  padding: 5px;
}

td {
  border: 1px solid #ddd;
  padding: 5px;
}
.num {
  border: 1px solid #ddd;
  width: 20px;
  display: inline-block;
  text-align: center;
  cursor: pointer;
}
</style>