<div id="example">
        <div class="title">
            <div>商品名称</div>
            <div>单价</div>
            <div>数量</div>
            <div>金额</div>
        </div>
        <div v-for="(item, index) in shop" class="content">
            <div>{{item.name}}</div>
            <div>{{item.price}}</div>
            <div>
                <button @click="reduceCount(index)" :disabled="item.count === 0">-</button>
                {{item.count}}
                <button @click="addCount(index)">+</button>
            </div>
            <div>{{item.totals}}</div>
        </div>
        <p>合计:{{totalprice()}}</p>
    </div>
    <script type="text/javascript">
        var exam = new Vue({
            el: '#example',
            data: {
                shop: [{ //定义商品信息数组
                    name: '女士连衣裙',
                    price: 499,
                    count: 0,
                    totals: 0
                }, {
                    name: '男士衬衫',
                    price: 399,
                    count: 0,
                    totals: 0
                }, {
                    name: '女士短袖',
                    price: 128,
                    count: 0,
                    totals: 0
                }, {
                    name: '男士短袖',
                    price: 138,
                    count: 0,
                    totals: 0
                }]
            },
            methods: {
                totalprice: function () {
                    var t = 0
                    for (var i = 0; i < this.shop.length; i++) {
                        t += this.shop[i].totals
                    }
                    return t
                },
                addCount: function (index) {
                    this.shop[index].count++
                    this.shop[index].totals = this.shop[index].price * this.shop[index].count
                },
                reduceCount: function (index) {
                    if (this.shop[index].count > 0) {
                        this.shop[index].count--
                        this.shop[index].totals = this.shop[index].price * this.shop[index].count
                    }
                }
            }
        })
    </script>
Vue.js 购物车实现:数量减至 0 不可再减

原文地址: https://www.cveoy.top/t/topic/nw7I 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录