【问题标题】:NuxtJS change query params and reload pageNuxtJS 更改查询参数并重新加载页面
【发布时间】:2021-05-24 19:32:50
【问题描述】:

我的 NuxtJS 应用程序中有一个接受查询参数的路由。我正在尝试实现允许用户更改查询参数并重新加载页面的逻辑。

我试过了:

// this does not work because I'm already in "mypage" and "push" does not reload the same page
this.$router.push(`/mypage?param1=${value1}&param2=${value2}`)

// same result as above
this.$router.push({ path: '/mypage', query: {param1: value1, param2: value2}})

// this is able to change the query parameters but on reload they are reverted to the originals
this.$router.replace({ query: {param1: value1, param2: value2} })
window.location.reload()

// This reload the page but the query parameters are reverted as well
this.$router.go(`/mypage?param1=${value1}&param2=${value2}`)

有什么建议吗?

【问题讨论】:

  • 使用reload的目的是什么?
  • 更改查询参数后刷新页面但不起作用
  • 但是 Vue 是响应式的,应该预期更改会在不刷新的情况下发生。这不是一个好习惯

标签: vue.js vue-router server-side-rendering nuxtjs


【解决方案1】:

如果您只想更改查询参数而不重新加载页面,请使用Fabio Magarelli 解决方案:

window.history.pushState({},'',`/mypage?param1=${value1}&param2=${value2}`)

通过重新加载进行更改 - 使用这个:

this.$router.push({path: this.$route.path, query: { param1: 'param1', param2: 'param2' }})

【讨论】:

    【解决方案2】:

    您应该使用第二种方法来更新查询参数。

    this.$router.push({ path: '/mypage', query: {param1: value1, param2: value2}})
    

    强制重新加载页面确实是一种不好的做法,相反,您应该为查询设置观察者或计算者。

    例如

      watch: {
        '$route.query'() {
          // do something
        }
      },
    

    如果这对您不起作用,请提供有关您的问题的更多信息。

    【讨论】:

    • 感谢您的回答,如果我想用新参数重新加载页面,我会在观察者中放入什么?
    • 您始终可以使用 this.$router.go(0) 重新加载页面,但正如我在答案中所说,您真的不应该这样做,因为 NuxtJs 是反应式的。在 99% 的情况下,您可以通过其他方式(方法、vuex 等)解决问题。
    【解决方案3】:

    这只是一种解决方法:

    感谢:https://github.com/vuejs/vue-router/issues/1182#issuecomment-405326772

    我能够通过使用 javascript 解决此问题:

    window.history.pushState({},'',`/mypage?param1=${value1}&param2=${value2}`)
    window.location.reload()
    

    当然,这不是最佳解决方案,但它可以完成工作,直到有人在这里提出更合适的解决方案。谢谢。

    【讨论】: