我使用的是vue3。
我在组件的setup()
中有一个简单的自动完成小部件方法。
当用户将注意力从输入移开或进行选择时,我想隐藏自动完成下拉列表。为了做到这一点,我想检查我的输入元素的焦点状态,然而,Vue3似乎不喜欢我在安装元素之前的设置函数中这样做。最好的方法是什么?
我的组件看起来像这样:
<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,
}
我尝试过在onMounted
方法中包装元素状态,但它仍然抛出一个错误。
有正确的方法吗?我本来打算使用on-change函数来重置全局变量,但希望有一种简单的方法可以检查元素的焦点状态,而无需使用该方法。
您可能正在查找模糊或聚焦事件。
<input ref="postcode_input" @blur="hidePopup" @input="hidePopup">