Reputation: 13450
Template:
<button @click="redirect">Search</button>
<input v-model="searchQuery" v-on:keyup.enter="redirect" type="text">
Js script:
export default {
methods: {
redirect: function() {
if (this.searchQuery) {
this.$router.push({
name: 'tag',
params: {
tag: this.searchQuery
}
})
}
}
},
data() {
return {
searchQuery: ''
}
}
}
Here's the problem. If I click enter in the input, the redirection will work fine to the route with name tag
. If I click the button, the redirection will try to happen (I will see in browser url the change) but then instantly it will go back to the existing page
Upvotes: 0
Views: 2810
Reputation: 20845
I suspect that you have a <form>
tag wrapping the button and input. And the button
click trigger form submission so the page reload and returns to the same page.
Try modifying the click event into @click.prevent="redirect"
.
.prevent
will have the effect of event.preventDefault()
on the click event.
Will delete this answer if using <form>
is not the reason.
Upvotes: 2
Reputation: 16485
I don't know what is causing the error. Maybe check if this.searchQuery
has a value when you try to redirect with the click event. In either case, I think you are better of using <router-link />
to redirect your page. If you want the router-link to look like a button then pass tag='button'
as in this example:
<router-link tag='button' :to="{ name: 'tag', params: { tag: this.searchQuery }}"> search </router-link>
Upvotes: 0