0

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

1
  • the provided code has no problem. The issue is probably caused by something else. Commented Mar 2, 2018 at 13:43

2 Answers 2

2

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.

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

1 Comment

Thanks Jacob. The form was the issue indeed. prevent helped 👍🏻
0

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>

1 Comment

Yes that will work. But with that example then the searchQuery is empty there is a console log warning

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.