You need to enable JavaScript to run this app. Vue/Laravel项目中如何根据购物车items的delivers_today属性统计deliver_later_num
优惠活动
大模型
产品
解决方案
定价
更多

Vue/Laravel项目中如何根据购物车items的delivers_today属性统计deliver_later_num

Laravel项目Vue购物车deliver_later_num计数实现

核心需求

开发Laravel电商项目过程中,需要实现购物车deliver_later_num变量的自动统计:

  • 统计规则:遍历Vue购物车组件items数组内的所有商品项,若某商品携带的delivers_today属性值为0,则deliver_later_num累加1
  • 当前待决策问题:该统计逻辑应该写在Vue模板渲染侧,还是写在组件逻辑侧
  • 商品列表最终通过Blade模板渲染输出

现有代码实现

Vue购物车组件初始逻辑

cartContent = new Vue({
    el: '#cartList',
    data: {
        items: [], // 存储所有购物车商品项
        deliver_later_num: 0, // 需要计算的晚配送商品计数
    },
    methods: {
        remove: function (product_id) {
            removeProductIfFromCart(product_id);
        },
        incQuantity: function (product_id){
            incCart(product_id)
        },
        decQuantity: function (product_id){
            decCart(product_id)
        },
    }
})

购物车渲染模板代码

<div id="cartList">
    <div v-for="item in items" class="items col-xs-12 col-sm-12 col-md-12 col-lg-12 clearfix">
        <div class="info-block block-info clearfix" v-cloak>
            <div class="square-box pull-left">
                <img :src="item.attributes.image" class="productImage" width="100" height="105" alt="">
            </div>
            <h6 class="product-item_title">@{{ item.name }}</h6>
            <p class="product-item_quantity">@{{ item.quantity }} x @{{ item.attributes.friendly_price }}</p>
            <ul class="pagination">
                <li class="page-item">
                    <button v-on:click="decQuantity(item.id)" :value="item.id" class="page-link" tabindex="-1">
                        <i class="fa fa-minus"></i>
                    </button>
                </li>
                <li class="page-item">
                    <button v-on:click="incQuantity(item.id)" :value="item.id" class="page-link" >
                        <i class="fa fa-plus"></i>
                    </button>
                </li>
                <li class="page-item">
                    <button v-on:click="remove(item.id)" :value="item.id" class="page-link" >
                        <i class="fa fa-trash"></i>
                    </button>
                </li>
                <!-- 隐藏字段存储商品当日配送标记,值为0时需要计入晚配送计数 -->
                <input hidden class="delivers_today_state" type="text" :value="item.attributes.delivers_today">
            </ul>
        </div>
    </div>
</div>

Laravel后端控制器相关逻辑

当前加购逻辑已经将商品的deliverstoday字段存入购物车项的attributes中,随购物车内容接口返回给前端:

// 加购方法
public function add(Request $request){
    $item = Items::find($request->id);
    $restID = $item->category->restorant->id;

    // 校验同餐厅加购逻辑
    $canAdd = false;
    if(Cart::getContent()->isEmpty()){
        $canAdd = true;
    }else{
        $canAdd = true;
        foreach (Cart::getContent() as $key => $cartItem) {
            if($cartItem->attributes->restorant_id."" != $restID.""){
                $canAdd = false;
                break;
            }
        }
    }

    if($item && $canAdd){
        $cartItemPrice = $item->price;
        $cartItemName = $item->name;
        $theElement = "";

        // 变体价格处理
        if($request->variantID){
            $variant = Variants::findOrFail($request->variantID);
            $cartItemPrice = $variant->price;
            $cartItemName = $item->name." ".$variant->optionsList;
        }

        // 附加项价格处理
        foreach ($request->extras as $key => $value) {
            $cartItemName .= "\n+ ".$item->extras()->findOrFail($value)->name;
            $cartItemPrice += $item->extras()->findOrFail($value)->price;
            $theElement .= $value." -- ".$item->extras()->findOrFail($value)->name."  --> ". $cartItemPrice." ->- ";
        }

        // 加入购物车,存储delivers_today属性
        Cart::add(
            (new \DateTime())->getTimestamp(),
            $cartItemName,
            $cartItemPrice,
            $request->quantity,
            array(
                'id' => $item->id,
                'variant' => $request->variantID,
                'extras' => $request->extras,
                'restorant_id' => $restID,
                'image' => $item->icon,
                'friendly_price' => Money($cartItemPrice, env('CASHIER_CURRENCY','usd'),true)->format(),
                'delivers_today' => $item->deliverstoday
            )
        );

        return response()->json([
            'status' => true,
            'errMsg' => $theElement
        ]);
    }else{
        return response()->json([
            'status' => false,
            'errMsg' => __("You can't add items from other restaurant!")
        ]);
    }
}

// 获取购物车内容方法
public function getContent(){
    return response()->json([
        'data' => Cart::getContent(),
        'total' => Cart::getSubTotal(),
        'status' => true,
        'errMsg' => ''
    ]);
}

推荐实现方案

统计逻辑绝对不要放在Vue模板里实现,直接在Vue组件中通过计算属性从源数据实时统计,是最稳定、最少bug的实现方式:

  • 逻辑分层清晰:模板只负责视图渲染,复杂数据统计逻辑放在组件侧,易调试维护
  • 自动响应更新:只要items数组发生变化(加购、删除、修改数量、清空购物车),计算属性会自动重新计算值,不需要手动写加1/减1的逻辑,彻底避免手动维护计数不同步的问题
  • 避免重复计算:在模板的v-for循环里写累加逻辑,会在每次重渲染时重复触发计数,很容易出现数值翻倍的bug

具体修改代码

删掉原来data里手动维护的deliver_later_num,新增computed计算属性:

cartContent = new Vue({
    el: '#cartList',
    data: {
        items: [] // 仅保留购物车源数据数组
    },
    computed: {
        deliver_later_num() {
            // 实时统计所有delivers_today为0的商品数量
            return this.items.filter(item => {
                // 做类型兼容处理,避免后端返回字符串"0"无法匹配数字0的问题
                return Number(item.attributes.delivers_today) === 0
            }).length
        }
    },
    methods: {
        // 原有方法保持不变即可
        remove: function (product_id) {
            removeProductIfFromCart(product_id);
        },
        incQuantity: function (product_id){
            incCart(product_id)
        },
        decQuantity: function (product_id){
            decCart(product_id)
        },
    }
})

模板侧调整注意事项

  • 原代码里的隐藏delivers_today输入框可以直接删除,不需要把字段值存在DOM节点里,所有数据直接从item.attributes里读取即可
  • 需要展示晚配送商品数量的位置,直接引用deliver_later_num变量即可,比如:当前购物车共{{ deliver_later_num }}件商品支持预约配送,不需要写额外的赋值逻辑

内容的提问来源于stack exchange,提问作者Hatem TEMIMI

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.13 09:36:03