2
votes

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.

1

1 Answers

5
votes

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).