'NuxtJS change query params and reload page

I have a route in my NuxtJS application that accept query parameters. I'm trying to implement a logic that allow the user to change the query parameters and reload the page.

I tried:

// 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}`)

Any suggestions?



Solution 1:[1]

You should use the 2nd method to update query params.

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

It's really a bad practice to force reload a page, instead, you should set up a watcher or a computed for your query.

E.g.

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

If this doesn't work for your please provide more information about your problem.

Solution 2:[2]

This is only a workaround:

thanks to this: https://github.com/vuejs/vue-router/issues/1182#issuecomment-405326772

I was able to work around the issue by using javascript:

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

of course this is not an optimal solution but it gets the work done until someone come out with a more proper solution here. thanks.

Solution 3:[3]

if u want only to change query param without reloading the page, use Fabio Magarelli solution:

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

for change with reload - use this:

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

Solution 4:[4]

You can do it use promise.then() and $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();
});

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MikodanicI
Solution 2
Solution 3 itzhar
Solution 4 yuhenabc