3

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 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.