书籍购物车

image.png

购物车数据

const books= [
  {
    id: 1,
    name: '《算法导论》',
    date: '2006-9',
    price: 85.00,
    count: 1
  },
  {
    id: 2,
    name: '《UNIX编程艺术》',
    date: '2006-2',
    price: 59.00,
    count: 1
  },
  {
    id: 3,
    name: '《编程珠玑》',
    date: '2008-10',
    price: 39.00,
    count: 1
  },
  {
    id: 4,
    name: '《代码大全》',
    date: '2006-3',
    price: 128.00,
    count: 1
  }
];

动态展示购物车数据(v-for)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div id="app"></div>
    <template id="my-app">
        <table>
            <thead>
                <th>序号</th>
                <th>书籍名称</th>
                <th>出版日期</th>
                <th>价格</th>
                <th>购买数量</th>
                <th>操作</th>
            </thead>
            <tbody>
                <tr v-for="book, index in books" :key="book.id">
                    <td>{{index + 1}}</td>
                    <td>{{book.name}}</td>
                    <td>{{book.date}}</td>
                    <td>{{fromatPrice(book.price)}}</td>
                    <td>
                        <button>-1</button>
                        {{book.count}}
                        <button>+1</button>
                    </td>
                    <td>
                        <button>移除</button>
                    </td>
                </tr>
            </tbody>
        </table>
    </template>
    <script src="../js/vue.js"></script>
    <script src="./index1.js"></script>
    
</body>
</html>

image.png

处理点击事件 v-on

<td>
    <button @click="decrement(index)">-1</button>
    {{book.count}}
    <button @click="increment(index)">+1</button>
</td>
<td>
    <button @click="remove(index)">移除</button>
</td>
methods: {
  increment(index) {
    this.books[index].count++;
  },
  decrement(index) {
    if (this.books[index].count > 1) this.books[index].count--;
  },
  remove(index) {
    this.books.splice(index, 1);
  },
  fromatPrice(price) {
    return "¥" + price;
  },
}

动态绑定属性值

  • 当 数量为 1 的时候,减去的按钮应该被禁用。
  • 需要给该按钮动态的绑定 disabled 属性
<button :disabled="1 === book.count" @click="decrement(index)">-1</button>

image.png

使用计算属性 动态统计 总价格

<h2>总价格:{{totalPrice}}</h2>
computed: {
  totalPrice() {
    return (
      "¥" +
      this.books.reduce((pre, curr) => {
        return pre + curr.price * curr.count;
      }, 0)
    );
  },
}

image.png