Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make query parameter with vue router reactive

I am trying to build a search page with Vue and I want the query text that the user enters in an input field to be reactive with the query parameter in the URL eg:

input: foo url: http://localhost:8080/search?query=foo

and if the user continues to type bar in the input field, I want to get the URL to updated to http://localhost:8080/search?query=foobar without the navigating via the router.

like image 386
abks Avatar asked Jun 04 '26 16:06

abks


1 Answers

If you make $route.query the source of truth, then when you want to mutate its value you just need to do a $router.replace() operation with the updated query value.

Off the cuff:

<input :value="$route.query.q" @input="onInput">
onInput(e) {
  this.$router.replace({
    query: {
      ...this.$route.query,
      q: e.target.value,
    }
  })
}

The ...this.$route.query is to preserve any other query parameters that may exist; if you only have q then it isn't necessary (also you may need to use Object.assign() instead since support for object spread syntax is patchy right now).

like image 152
Decade Moon Avatar answered Jun 07 '26 08:06

Decade Moon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!