Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 455
Fabio Magarelli Avatar asked Oct 12 '25 00:10

Fabio Magarelli


2 Answers

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.

like image 81
MikodanicI Avatar answered Oct 14 '25 18:10

MikodanicI


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.

like image 27
Fabio Magarelli Avatar answered Oct 14 '25 18:10

Fabio Magarelli