1

I'm trying to implement Autocomplete from scratch in Vue, however I have issue with selecting option in dropdown. I'm enabling (shownig) this dropdown on input click or if user types something. Then, on focus outside of input I want to get rid of dropdown. However, it means that when I select something inside dropdown, I'm closing dropdown instead of triggering selectOption. How to keep both v-on:focusout on input and @click="selectOption(option)" on dropdown option? So far, the only way to make selectOption work was to remove focusout, which isn't something I want...

<template>
  <div>
    <input
      type="text"
      v-on:input="enableDropdown"
      v-on:click="enableDropdown"
      v-on:focusout="disableDropdown"
    />
    <div class="options-dropdown" v-if="showDropdown">
      <div
        class="option"
        v-for="option in options"
        :key="option"
        @click="selectOption(option)"
      >
        {{ option }}
      </div>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      options: [
        "java",
        "c#",
        "c++"
      ],
      showDropdown: false,
    };
  },
  methods: {
    enableDropdown() {
      this.showDropdown = true;
    },
    disableDropdown() {
      this.showDropdown = false;
    },
    selectOption($event) {
      console.log($event);
    },
  },
};
</script>
Weeedooo
  • 501
  • 8
  • 25
  • ref: https://stackoverflow.com/a/47944833/10247526 mousedown is called before focusout, unlike click, so the easiest solution is to replace your click with mousedown. – heyt0pe Mar 10 '22 at 20:33

1 Answers1

0

You should check in you disableDropdown event if the current focus is in the options-dropdown.

Something like this

disableDropdown() {    
  this.showDropdown = this.$refs.optionsDropdown === document.activeElement;
}

This way it will return true if your options-dropdown is focused (you'll also need to add the ref tag to it).

maxshuty
  • 9,708
  • 13
  • 64
  • 77