vue--16 购物车加减

发布时间 2023-06-25 16:26:10作者: 山雨欲來風滿楼

效果:

 代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>16购物车加减</title>
    <!--        <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>-->
    <script src="./js/vue.js"></script>
    <!--引入bootstrap-->
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<!--下面的class="container"是bootstrap的样式-->

<div class="container" id="app">
    <table class="table">
        <tr>
            <td>商品名称</td>
            <td>商品价格</td>
            <td>商品数量</td>
            <td>选择</td>
            <td>全选 <input type="checkbox" v-model="checkAll" @change="handleCheckAll"></td>
        </tr>
        <tr v-for="good in goods">
            <td>{{good.name}}</td>
            <td>{{good.price}}</td>
            <td>
                <button @click="good.count++">+</button>
                {{good.count}}
                <!--                <button @click="good.count&#45;&#45;">-</button>-->
                <button @click="handle_j(good)">-</button>

            </td>
            <td><input type="checkbox" v-model="checkGroup" :value="good" @change="handleCheckOne"></td>
        </tr>
    </table>
    选中的商品是:{{checkGroup}}
    <hr>
    方式2:总价格(实时计算):{{sumGoods_2()}}
</div>


</body>


<script>
    const {createApp} = Vue
    createApp({
        data() {
            return {
                goods: [
                    {id: 1, name: '铅笔', price: 1, count: 12},
                    {id: 2, name: '橡皮', price: 2, count: 5},
                    {id: 3, name: '文具盒', price: 10, count: 3},
                    {id: 4, name: '水杯', price: 30, count: 1},
                ],
                checkGroup: [],
                checkAll: false
            }

        },
        methods: {

            sumGoods_2() {
                let sumPrice = 0 // 定义变量
                for (i in this.checkGroup) {// i是索引
                    sumPrice += (this.checkGroup[i].price * this.checkGroup[i].count)
                }
                return sumPrice
            },
            //全选
            handleCheckAll() {
                if (this.checkGroup.length == this.goods.length) {
                    this.checkGroup = []
                    this.checkAll = false
                } else {
                    this.checkGroup = this.goods
                    this.checkAll = true
                }
            },
            handleCheckOne() {
                if (this.checkGroup.length != this.goods.length) {
                    this.checkAll = false
                } else {
                    this.checkAll = true
                }
            },
            handle_j(good) {
                if (good.count == 1) {
                    good.count = 1
                } else {
                    good.count--
                }
            }

        },

    }).mount('#app')


</script>
</html>