[英]Blur event cancels click event in Vue component
I have a search component in Vue.js
.我在
Vue.js
中有一个搜索组件。 When you type into the text input, a list of search results is fetched from the server, then displayed in a list beneath the search field.当您在文本输入中键入时,将从服务器获取搜索结果列表,然后显示在搜索字段下方的列表中。 When you click one of the results, the
submit
event fires.当您单击其中一个结果时,将触发
submit
事件。
However, now I tried adding a blur event to the text input, which should hide the list of results when the user clicks away from the input.但是,现在我尝试向文本输入添加一个模糊事件,当用户点击远离输入时,它应该隐藏结果列表。 This works fine, except for one crucial situation - clicking on a result no longer fires the
submit
event.这工作正常,除了一种关键情况 - 单击结果不再触发
submit
事件。
I understand why this is - the blur
event apparently fires before the click
event, and hides the results list before the click can be registered on one of the results.我明白为什么会这样 -
blur
事件显然在click
事件之前触发,并在点击可以注册到其中一个结果之前隐藏结果列表。 My question is, how do I get around this?我的问题是,我该如何解决这个问题? I need the results list to close when clicking outside the text input, but I obviously also need the
submit
method to function.在文本输入之外单击时我需要关闭结果列表,但我显然还需要
submit
方法到 function。
Here is the component in full:这是完整的组件:
<template>
<div class="search basic-search">
<input type="text" v-model="search_string" v-on:keyup="search" v-on:focus="activate" v-on:blur="inactivate" class="form-control search" placeholder="Search stocks" />
<div :class="['search-results', active === true ? 'active' : '']">
<div class="search-result" v-for="result in search_results" v-on:click="submit(result.id)">
{{ result.name }} ({{ result.ticker }})
</div>
</div>
</div>
</template>
<script>
export default {
data: function() {
return {
search_string : '',
search_results : [],
active : false
};
},
methods : {
search : function() {
const axios_data = {
_token : $('meta[name="csrf-token"]').attr('content'),
str : this.search_string
};
axios.post('/stock-search', axios_data).then(response => {
if(response.data.success){
this.search_results = response.data.stocks;
this.active = true;
}
});
},
activate : function() {
if(this.search_string !== '')
this.active = true;
},
inactivate : function() {
this.active = false;
},
submit : function(stock_id) {
document.location = "/graphs/" + stock_id;
}
}
}
</script>
You could delay the hiding of the box until click
fires您可以延迟隐藏框,直到
click
触发
inactivate : function() {
setTimeout( () => this.active = false, 100)
},
You may also try to use mousedown
instead of click
您也可以尝试使用
mousedown
而不是click
<div class="search-result" v-for="result in search_results" v-on:mousedown="submit(result.id)">
I don't know if the order of the events is determined, but mousedown should be triggered before blur.我不知道事件的顺序是否确定,但是mousedown应该在blur之前触发。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.