I am using vue3.
I have a simple auto-complete widget method in the setup()
of my component.
I want to hide the autocomplete dropdown when a user focuses away from input or makes a selection. To do this I want to check the focus status of my input element, however, Vue3 doesn't seem to like me doing this in a setup function which is technically before the element is mounted. What is the best way to do this?
my component looks something like this:
<input ref="postcode_input" ...>
...
setup() {
let searchTerm = ref('')
...
let postcode_input = ref(null) //attempt to access ref element
...
const searchLocalities = computed(() => {
if (searchTerm.value === '') {
return []
}
let matches = 0
//would like add a check for postcode_input focus == true here...
return postcodes.value.filter(locality => {
if (locality.locality.toLowerCase().includes(searchTerm.value.toLowerCase()) && matches < 10) {
matches
return locality
}
})
});
/* selection function to populate form */
const selectPostcode = (location) => {
selectedPostcode.value = location.postcode
searchTerm.value = location.locality
}
let selectedPostcode = ref('')
return {
searchTerm,
searchLocalities,
postcodes,
selectPostcode,
selectedPostcode,
}
I've tried wrapping the element status in an onMounted
method but it still throws an error.
Is there a correct way to do this? I was going to resort to an on change function resetting a global variable but was hoping there was a simple way to check the focus status of an element without resorting to that.
CodePudding user response:
You probably are looking for the blur or focus-out events.
<input ref="postcode_input" @blur="hidePopup" @input="hidePopup">