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

Vue3路由参数更新时Pinia Getter未更新的解决方法

Vue3路由参数更新时Pinia Getter不刷新列表的解决方法

问题描述

开发Vue3应用时,通过路由参数结合Pinia Store的Getter筛选条目列表,但路由参数更新后,列表不会重新获取。页面上的{{state}}能随路由变化更新,但是条目列表无变化。

组件代码

<script lang="ts" setup>
  import {useIncStore} from "@/store/inc";
  import {useRoute} from "vue-router";

  const route = useRoute()
  const state = Array.isArray(route.params.state) ? route.params.state[0] : route.params.state
  const incStore = useIncStore();

  // 以下两种方式均无效...
  const incs = incStore.getByState(state)
  // const incs = computed(() => incStore.getByState(state))
</script>

Store Getter代码

getters: {
  getByState(state) {
    return (s: string) => state.records.filter((rec: any) => rec.state === s)
  }
}

解决步骤

  • 让state成为响应式变量
    route.params本身是响应式的,但直接赋值的state是普通变量,路由更新时不会触发依赖追踪。需要用computed包裹:

    const state = computed(() => {
      return Array.isArray(route.params.state) ? route.params.state[0] : route.params.state
    })
    
  • 正确使用computed调用Getter
    Getter返回的是一个函数,需要在computed中传入响应式的state.value,这样参数变化时才会重新执行筛选:

    const incs = computed(() => incStore.getByState(state.value))
    

原因说明

之前的state是普通变量,路由参数更新时不会触发任何依赖更新,导致computed(如果用了的话)也不会重新计算;直接调用incStore.getByState(state)只会执行一次,不会追踪后续state或state.records的变化。用computed包裹后,会自动追踪state.value和state.records的变化,从而自动刷新列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:42:17