Reputation: 16364
I am making a data table with a search field in my application and I would like to implement the following behaviour:
When a user types a research, the URL gets updated. If a user clicks on a link and hit "back" from his navigator, he gets back to his last search.
For the moment, I am doing the following thing:
export default {
data () {
return {
search: ''
}
},
watch: {
search (value) {
this.$router.replace('/products?search=' + value)
}
}
}
As you can see, I am using the replace
function of the router. That allows me to make it work. And it's better than the push
method because if a user hits "back" during a search, he will go to his last page and not last research, and that's exactly what I want.
However, I don't like how I hard write the URL.
I would love to make something like that:
watch: {
search (value) {
let route = new Route(this.$route)
route.query.search = value
this.$router.replace(route.getPath())
}
}
Because, let's imagine that the user has other parameters like pagination or something like that, they would be erased. I would like a method that takes my actual url and add/replace a query string parameter.
Is this something I can achieve with Vue Router or do I need to do something else: Other package / Vanilla JS?
Upvotes: 0
Views: 143
Reputation: 754
Why not just use the object location parameter $router.replace
? Eg:
watch: {
search (value) {
this.$router.replace({ path: 'products', query: { search: value }})
}
}
Upvotes: 2