You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js点击添加按钮后无需刷新更新购物车商品数量

解决Vue购物车添加后无需刷新更新数量的问题

问题根源

  1. onMounted 仅在组件首次挂载时执行一次,点击添加商品后不会自动触发,所以新增商品后数量不会同步更新。
  2. getCurrentCartLength 函数逻辑冗余且误用了 async:通过 forEach 循环逐个赋值 count,最终结果其实就是数组长度,但这种写法完全多余;而且函数内没有异步操作,async 属于无效标注。

修复方案

1. 简化购物车数量计算逻辑

直接通过购物车数组的长度设置数量,去掉冗余循环和不必要的异步标识:

const getCurrentCartLength = () => {
  count.value = currentCart?.length || 0;
};

2. 在添加商品后主动触发数量更新

在完成购物车数据更新和localStorage存储后,立即调用getCurrentCartLength()同步数量,示例如下:

// 示例添加商品方法
const addToCart = (product) => {
  // 处理购物车数据:检查商品是否已存在,更新数量或新增条目
  const existingItem = currentCart.find(item => item.prId === product.prId);
  if (existingItem) {
    existingItem.prQty += 1;
  } else {
    currentCart.push({
      prId: product.prId,
      prQty: 1,
      prSet: product.prSet
    });
  }

  // 更新localStorage
  localStorage.setItem('cart', JSON.stringify(currentCart));

  // 立即同步购物车数量
  getCurrentCartLength();
};

3. 确保购物车数据是响应式的

如果currentCart不是响应式变量,需要用ref或reactive声明,让Vue能跟踪数据变化:

import { ref, onMounted } from 'vue';

// 初始化响应式购物车数据,从localStorage读取
const currentCart = ref(JSON.parse(localStorage.getItem('cart') || '[]'));
const count = ref(0);

onMounted(() => {
  // 组件挂载时初始化数量
  getCurrentCartLength();
});

完整调整后的代码片段

<script setup>
import { ref, onMounted } from 'vue';

const currentCart = ref(JSON.parse(localStorage.getItem('cart') || '[]'));
const count = ref(0);

const getCurrentCartLength = () => {
  count.value = currentCart.value.length;
};

onMounted(() => {
  getCurrentCartLength();
});

// 添加商品到购物车
const addToCart = (product) => {
  const existingItem = currentCart.value.find(item => item.prId === product.prId);
  if (existingItem) {
    existingItem.prQty += 1;
  } else {
    currentCart.value.push({
      prId: product.prId,
      prQty: 1,
      prSet: product.prSet
    });
  }
  localStorage.setItem('cart', JSON.stringify(currentCart.value));
  getCurrentCartLength();
};
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:40:29