首页 文章

使Vue路由器查询在父组件级别保持不变

提问于
浏览
3

我有一个应用程序,其中组件 Foo 用作路径的模板, app/foo . 该组件具有子组件,这些子组件也用作路径的模板: app/foo/barapp/foo/baz 等 .

我将全局 vuex store对象绑定到路由的 query 属性,以便如果对象设置为 { a: 1, b: 2 } ,则url参数将更改为 ?a=1&b=2 ;如果用户将参数更改为 ?a=0&b=0 ,则对象将更新为 { a: 0, b: 0 } . 这一切都按预期工作 .

我遇到的麻烦是,当我然后路由到 app/foo 下的任何路径时,我丢失了路径的 query 属性,并且url params消失了 .

我可以像这样动态传递 query 对象:

this.$router.push({ name: 'bar', query: this.$route.query });

但是,这很快就难以维持 .

我知道Vue Router提供added life-cycle events,我想我应该能够在 Foo 组件的 beforeRouteUpdate 事件上更新查询 . 我做了几次不同的尝试,但没有骰子:

beforeRouteUpdate (to, from, next) {
  // This gives me an error saying that the query is read-only 
  to.query = from.query; 

  // This does not update the query
  this.$router.replace({ query: from.query })

  next();
},

编辑:

我还尝试在 $route 上设置一个观察程序,以便在路由更改时替换查询 . 但是,这会导致无限循环:

watch: {
  $route(to, from) {
    this.$router.replace({ query: from.query });
  }
}

有没有人知道如何使Vue Router查询在组件级持久化?

1 回答

  • 1

    基于@ craig_h的评论,我在 $route 上添加了一个观察者:

    watch: {
      $route(to, from) {
        if (to.path != from.path) { // to prevent an infinite loop
          this.$router.replace({ query: from.query })
        }
      }
    }
    

    这适用于大多数情况,除非组件偶然路由到当前路由 . 在这种情况下,查询仍然丢失,因为 to.pathfrom.path 值相同 .

    我的解决方法是将检查添加到可能路由到当前路由的组件:

    if ((name != this.$route.name) || (params != this.$route.params)) {
      this.$router.push({ name, params });
    }
    

    这有效,但仍然不理想 .

相关问题