javascriptvuejs3primevue

Primevue3. How to do not close dropdown when selecting an item from the options?


Is it possible not to close options when selecting one of them, when using the standard autocomplete component? I use this component for the user to select his last name, first name, and patronymic. I get the data dynamically on request after each character is entered. But the first time you click on one of the options, the dropdown closes. I need its state to always be open until the user loses focus on the input.

I saw that there is such a topic on github and this is what I need. But I understood that this feature was not transferred to production, since I do not see any mention of this in the documentation

I use Primevue 3.53

<template>
  <AutoComplete
    :modelValue="modelValue"
    @update:modelValue="emits('update:modelValue', $event)"
    :suggestions="searchData"
    @complete="search"
    appendTo="self"
  />
</template>
<script setup>
const search = async () => {
  try {
    const res = await $fetch(URL_DADATA, {
      method: 'POST',
      body: { query: props.modelValue },
      params: { token }
    })
    searchData.value = res.suggestions.map((i) => i.value)
  } catch (err) {
    console.error(err)
  } finally {
  }
}
</script>

I tried to write custom events for the component, but nothing worked.


Solution

  • <template>
      <AutoComplete
        ref="instance"
        v-bind="{ onItemSelect, onHide }"
      />
    </template>
    
    <script setup>
    import { ref } from 'vue'
    
    const instance = ref(null)
    const shouldReopen = ref(false)
    
    const openDropdown = () => instance.value?.show()
    const onItemSelect = () => {
      shouldReopen.value = true
    }
    const onHide = () => {
      if (shouldReopen.value) {
        openDropdown()
        shouldReopen.value = false
      }
    }
    </script>
    

    Working example 1.

    Change contents of onItemSelect to match your business logic (I'm guessing you only want to re-open the dropdown in some cases) 2.


    Notes:

    1 - <AutoComplete v-bind="{ onItemSelect, onHide }" /> is shorthand for

    <AutoComplete @item-select="onItemSelect" @hide="onHide" />
    

    2 - Make sure your users can intuitively close the dropdown and exit the input process without hassle - not being able to close a dropdown could be a frustrating experience.