Reputation: 1701
I have prepared a fiddle: https://jsfiddle.net/frvuw35k/
<div id="app">
<h2>Vue Event Test</h2>
<form @submit.prevent>
<div class="form-group row">
<div class="col-sm-12 input-group">
<input v-model="search" class="form-control" placeholder="Search users by Display Name"
@keyup.enter="doSearch">
<div class="input-group-append">
<button class="btn btn-primary" :disabled="!search" type="button"
@click.prevent="doSearch">
Search
</button>
</div>
</div>
</div>
<div class="form-group row">
<div class="col-12">
<button v-if="showButton" class="btn btn-info"
@click.prevent="doSthElse">Do something else</button>
</div>
</div>
</form>
</div>
new Vue({
el: "#app",
data: {
search: null,
showButton: false
},
methods: {
doSearch: function(){
console.log('do search:', this.search)
this.showButton = true
},
doSthElse: function(){
console.log('do something else')
}
}
})
This simulates something I have faced in my Vue application.
There is a second button, that is shown when a condition is meet. This condition is a result of a search, that is triggered by hitting enter key on the input.
On a second enter after the condition was meet, also if one has clicked somewhere else and put the focus back on the input, the second button is triggered...
I don't see the reason and haven't found out how to avoid it so fare.
Upvotes: 1
Views: 355
Reputation: 3910
Use this: You need to user @keydown and prevent modifier
<input v-model="search" class="form-control" placeholder="Search users by Display Name"
@keydown.enter.prevent="doSearch"/>
Upvotes: 1
Reputation: 7136
This is caused by the browser behavior in a form.
The normal behavior is that when a user press down the Enter key on an input, it will submit the form.
Also, to submit a form, the browser will look for a button in the form, which is your "Do something else" button in your case.
So when the user presses Enter, it will trigger a button press on your last button, calling the doSthElse
method.
To fix this, simply add the a @keydown.enter.prevent
listener on the form to prevent the default behavior to trigger.
I updated your fiddle with the fix : https://jsfiddle.net/vy57d63f/
Upvotes: 3