Vue.js实现购物车功能简单拓展(商品数量的变化、总价的变化)

目录

任务描述:

效果图:

代码如下:


任务描述:

       点击数量按钮实现商品数量的变化,同时商品的总价和合计金额随之发生改变。此外,当商品的数量小于1时触发弹窗警告。

效果图:

代码如下:

<body>
    <div id="shoppingCart">
        <table border="1">
            <thead>
                <tr>
                    <th>
                        名称
                    </th>
                    <th>
                        单价
                    </th>
                    <th>
                        数量
                    </th>
                    <th>
                        总价
                    </th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(value, index) in phoneInfo">
                    <th>
                        {{value.name}}
                    </th>
                    <th>
                        {{value.price}}
                    </th>
                    <th>
                        <button @click="sub(index)">-</button>
                        <input type="text" v-model="value.count">
                        <button @click="add(index)">+</button>
                    </th>
                    <th>
                        {{value.price * value.count}}
                    </th>
                </tr>
                <tr>
                    <th>
                        合计:{{calu}}
                    </th>
                </tr>
            </tbody>
        </table>
    </div>
    <script>
        var vm = new Vue({
            el: '#shoppingCart',
            data: {
                phoneInfo: [
                    {
                        name: '商品01',
                        price: 12345,
                        count: 1
                    },
                    {
                        name: '商品02',
                        price: 23456,
                        count: 1
                    }
                ]
            },
            computed: {
                calu: function () {
                    var total = 0;
                    this.phoneInfo.forEach(function (s) {
                        total += s.price * s.count;
                    });
                    retuen total;
                }
            },
            methods: {
                add: function (index) {
                    this.phoneInfo[index].count++;
                },
                sub: function (index) {
                    if (this.phoneInfo[index].count > 1) {
                        this.phoneInfo[index].count--;
                    } else {
                        alert("数量不能为0");
                    }
                }
            }
        })
    </script>
</body>

觉得还不错就给个赞吧!

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值