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

Gridsome的mounted方法仅在页面重载时触发,页面跳转时不执行如何解决?

问题原因

你遇到的是Vue路由组件复用导致的生命周期不触发问题:当跳转的路由对应同一个组件时,Vue为了性能会复用已有的组件实例,不会重新执行销毁、挂载流程,因此mounted钩子仅在页面首次加载/刷新时触发,路由跳转时不会运行。

可行解决方案

方案1:监听路由变化(推荐,性能最优)

新增watch监听路由对象,路由发生变化时自动触发数据拉取逻辑,加上immediate配置后首次加载也会自动执行,可直接替代mounted里的手动调用:

methods: {
  // 原有fetchInventory方法不变
  async fetchInventory(data = {}) {
    try {
      this.isLoading = true;
      const result = await index.search("", {hitsPerPage: 12});
      this.auctions = result.hits;
      this.totalItems = result.nbHits;
      this.totalPages = result.nbPages;
      this.isLoading = false;
    } catch (error) {
      this.isLoading = false;
      console.log(error);
    }
  },
},
watch: {
  '$route': {
    immediate: true,
    handler() {
      this.fetchInventory()
    }
  }
}
// 原mounted逻辑可直接删除,immediate会保证首次加载自动执行

方案2:强制组件销毁重建(适合快速修改)

给路由出口router-view绑定唯一key,强制路由跳转时销毁旧组件、重建新组件,原有mounted逻辑无需修改即可每次触发:

<router-view :key="$route.fullPath" />

方案3:使用路由导航守卫

用Vue Router提供的beforeRouteUpdate钩子,在路由更新且组件复用时触发数据拉取:

methods: {
  // 原有fetchInventory方法不变
},
beforeRouteUpdate(to, from, next) {
  this.fetchInventory()
  next()
},
mounted() {
  this.fetchInventory()
}
注意事项

确保代码中的index变量已正确挂载到当前组件实例或者全局作用域,避免出现未定义的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:06:04