vue购物车完整功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue购物车完整功能

qlj224   2022-05-23 我要评论

vue实现购物车商品单选、全选及商品数量和总价计算,供大家参考,具体内容如下

效果展示

HTML

<template>
  <div class="buyCar">
    <header-bar
      title="购物车商品"
      :show-line="true"
    />
    <div class="content">
      <table>
        <thead>
          <tr>
            <th>商品总数: {{ total }}</th>
            <th>商品总价: {{ totalPrice }}</th>
            <th>
              <input
                v-model="AllChecked"
                type="checkbox"
                @click="checkAll"
              >
              全选
            </th>
          </tr>
        </thead>
        <tbody>
          <tr
            v-for="(item, index) in list"
            :key="index"
          >
            <td>{{ item.name }}</td>
            <td>单价: {{ item.price }}</td>
            <td>
              <input
                v-model="item.isChecked"
                type="checkbox"
                @click="check(item)"
              >
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

JS

<script>
import HeaderBar from '../components/header/index.vue';

export default {
  name: 'BuyCar',
  components: {
    HeaderBar,
  },
  data() {
    return {
      list: [
        {
          name: '商品1',
          price: 1111,
          isChecked: false,
        },
        {
          name: '商品2',
          price: 2222,
          isChecked: false,
        },
        {
          name: '商品3',
          price: 3333,
          isChecked: false,
        },
        {
          name: '商品4',
          price: 4444,
          isChecked: false,
        },
        {
          name: '商品5',
          price: 5555,
          isChecked: false,
        },
      ],
      total: 0,
      // 是否已全选
      AllChecked: false,
    };
  },
  computed: {
    totalPrice() {
      let prices = 0;
      this.list.forEach(item => {
        if (item.isChecked) {
          prices += item.price;
        }
      });
      return prices;
    },
  },
  methods: {
    // 单选
    check(item) {
      if (!item.isChecked) {
        this.total++;
      } else {
        this.total--;
      }
      this.AllChecked = this.total === this.list.length;
    },
    // 全选和反选
    checkAll() {
      const AllChecked = this.AllChecked;
      this.list.forEach(item => {
        item.isChecked = !AllChecked;
      });
      this.AllChecked = !this.AllChecked;
      this.total = this.AllChecked ? this.list.length : 0;
    },
  },
};
</script>

CSS

<style lang="less" scoped>
.buyCar {
  height: 100%;
  display: flex;
  flex-direction: column;
  .content {
    height: calc(100vh);
    padding: 45px 15px 15px;
    table {
      text-align: center;
      border-collapse: collapse;
      border-spacing: 0;
    }
    td,
    th {
      width: 200px;
      height: 20px;
      border: 1px solid #000;
    }
    input {
      width: 20px;
      height: 20px;
    }
  }
}
</style>

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们