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

Vue.js中如何在特定条件下点击导航栏购物车按钮刷新页面?

解决方案

核心问题是你判断当前页面路径的条件写错了,把/pathname换成MyCart页面的实际路由路径(比如/mycart,根据你的项目路由配置调整),同时优化逻辑确保不同页面触发对应行为:

修改后的TopNavBar.vue代码:

<template>
  <ul>
    <li>
      <a class="link" href="/shop">Shop</a>
    </li>
    <li class="userIcons" @click="showmyCart">
      <span class="link">MYCart <i class="fas fa-shopping-cart"></i></span>
    </li>
  </ul>
</template>

<script>
import MyMiniCart from "./MyMiniCart";

export default {
  name: "TopNavBar",
  methods: {
    showmyCart() {
      // 获取当前页面路径
      const currentPath = window.location.pathname;
      // 替换成你的MyCart页面实际路由路径,比如/mycart
      if (currentPath === '/mycart') {
        // 在MyCart页面时刷新整个页面
        window.location.reload();
      } else {
        // Shop页面或其他页面时,执行弹出迷你购物车的逻辑
        // 这里放你原来的弹出迷你购物车代码,比如调用迷你购物车的显示方法
      }
    }
  }
}
</script>

更优雅的Vue路由判断方式

如果你的项目使用Vue Router,建议用this.$route.path获取当前路由,比直接操作window.location更贴合Vue生态:

showmyCart() {
  if (this.$route.path === '/mycart') {
    window.location.reload();
  } else {
    // 弹出迷你购物车逻辑
  }
}

注意:请确保/mycart是你MyCart页面的实际路由路径,如果你的路由配置是其他路径(比如/cart),要对应修改判断条件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 07:50:26