Performing a click event on element of a div that is hiding at the same time

Viewed 53

I wrote a simple .vue file that is supposed to show a text input, that when focused displays a list of items. What I am struggling with is that I would like that when i click on an item, it sets the value of the text input to this item. However, right now with my code, the div containing the items hides before the click event triggers.

How can I do to perform the click event before the hiding ?

Here is my code :

<script>
export default {
    name: 'ListCompletion',
    data() {
        return {
            placeholder: "Gamertag",
            items: ['1', '2', '3', '4'],
            toggle: false
        }
    }
};
</script>

<template>
    <div class="Container">
        <input ref="input" type="text" :placeholder="placeholder" @focus="toggle = true" @blur="toggle = false" />
        <div v-show="toggle" class="list-group-flush">
            <button type="button" class="list-group-item list-group-item-action" v-for="item in items" @click="$refs.input.value = item">
                {{ item }}
            </button>
        </div>
    </div>
</template>

Thanks in advance for the help.

2 Answers

you could try @mousedown instead. It should trigger before the @blur event.

<script>
export default {
    name: 'ListCompletion',
    data() {
        return {
            placeholder: "Gamertag",
            items: ['1', '2', '3', '4'],
            toggle: false
        }
    }
};
</script>

<template>
    <div class="Container">
        <input ref="input" type="text" :placeholder="placeholder" @focus="toggle = true" @blur="toggle = false" />
        <div v-show="toggle" class="list-group-flush">
            <button type="button" class="list-group-item list-group-item-action" v-for="item in items" @mousedown="$refs.input.value = item">
                {{ item }}
            </button>
        </div>
    </div>
</template>

You can use setTimeout:

new Vue({
  el: "#demo",
  data() {
    return {
      placeholder: "Gamertag",
      items: ['1', '2', '3', '4'],
      toggle: false
    }
  },
  methods: {
    handleToggle() {
      setTimeout(() => this.toggle = false, 500)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div class="Container">
    <input ref="input" type="text" :placeholder="placeholder" 
            @focus="toggle = true" @blur="handleToggle"  />
    <div v-show="toggle" class="list-group-flush" >
      <button type="button" class="list-group-item list-group-item-action"
              v-for="item in items" :key="item" @click="$refs.input.value = item">
        {{ item }}
      </button>
    </div>
  </div>
</div>

Related