基本购物车

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="vue.js"></script>

</head>
<body>
<div id="app">
    <table>
        <thead>
        <td>
            id
        </td>
        <td>
            name
        </td>
        <td>
            price
        </td>
        <td>
            count
        </td>
        <td>
            <input type="checkbox" v-model="chooseAll" @change="handleAll"> {{chooseAll}}
        </td>
        </thead>
        <tr v-for="good in goodList">
            <td>{{good.id}}</td>
            <td>{{good.name}}</td>
            <td>{{good.price}}</td>
            <td>
                <button @click="handleJian(good)">-</button>
                {{good.count}}
                <button @click="good.count++">+</button>
            </td>
            <td><input type="checkbox" :value="good" v-model="chooseGoods" @change="handleOne">
            </td>
        </tr>
    </table>
    {{chooseGoods}}
    {{getTotalPrice()}}
</div>
</body>
<script>
    const app = Vue.createApp(
        {
            data() {
                return {
                    goodList: [
                        {id: '1', name: '小汽车', price: 150000, count: 2},
                        {id: '2', name: '鸡蛋', price: 2, count: 1},
                        {id: '3', name: '饼干', price: 10, count: 6},
                        {id: '4', name: '钢笔', price: 15, count: 5},
                        {id: '5', name: '脸盆', price: 30, count: 3},
                    ],
                    chooseGoods: [],
                    chooseAll: false
                }
            },
            methods: {
                getTotalPrice() {
                    let total = 0
                    // 方式1:es6 的 of 循环
                    for (item of this.chooseGoods) {
                        total += item.price * item.count
                    }
                    //方式2:数组的循环:循环计算选中的商品价格
                    this.chooseGoods.forEach(function (v, i) {
                        total += v.price * v.count
                    })
                    return total
                },
                handleAll() {
                    if (this.chooseAll) {
                        this.chooseGoods = this.goodList
                    } else {
                        this.chooseGoods = []
                    }
                },
                handleOne() {
                    this.chooseAll = (this.chooseGoods.length == this.goodList.length)
                },
                handleJian(good) {
                    if (good.count > 0){
                        good.count--
                    }
            }
        }}
    ).mount('#app')
</script>
</html>

image

posted @ 2022-10-25 19:14  Sherwin_szw  阅读(15)  评论(0编辑  收藏  举报