NuxtJS 更改查询参数并重新加载页面

NuxtJS change query params and reload page

我的 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}`)

有什么建议吗?

这只是一个解决方法:

多亏了这个:https://github.com/vuejs/vue-router/issues/1182#issuecomment-405326772

我使用 javascript:

解决了这个问题
window.history.pushState({},'',`/mypage?param1=${value1}&param2=${value2}`)
window.location.reload()

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

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

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

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

例如

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

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

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

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

重新加载更改 - 使用此:

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

您可以使用 promise.then() 和 $nuxt.refresh()

// before

this.$router.replace({ query: {param1: value1, param2: value2} })
window.location.reload()

// after

this.$router.replace({ query: {param1: value1, param2: value2} }).then(() => {
  this.$nuxt.refresh();
});