Blur事件取消Vue组件中的点击事件

jov*_*van 3 javascript vue.js

我有一个搜索组件Vue.js。当您在文本输入中键入内容时,将从服务器获取搜索结果列表,然后显示在搜索字段下方的列表中。当您单击其中一个结果时,submit会触发该事件。

但是,现在我尝试向文本输入添加模糊事件,当用户单击远离输入时,该事件应该隐藏结果列表。这工作得很好,除了一种关键情况 - 单击结果不再触发事件submit

我明白为什么会这样 - 该blur事件显然在该事件之前触发click,并在可以在其中一个结果上注册单击之前隐藏结果列表。我的问题是,我该如何解决这个问题?在文本输入外部单击时,我需要关闭结果列表,但显然我还需要该submit方法才能发挥作用。

这是完整的组件:

<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>
Run Code Online (Sandbox Code Playgroud)

Rad*_*iță 6

你可以推迟隐藏盒子直到click发生火灾

inactivate : function() {
   setTimeout( () => this.active = false, 100)
},
Run Code Online (Sandbox Code Playgroud)

您也可以尝试使用mousedown而不是click

<div class="search-result" v-for="result in search_results" v-on:mousedown="submit(result.id)">
Run Code Online (Sandbox Code Playgroud)

我不知道事件的顺序是否已确定,但 mousedown 应该在模糊之前触发。