To efficiently add auto-complete functionality, it is recommended to utilize the QSelect
component instead of the text-field QInput
.
Enhance Your Auto-Complete | Quasar Framework
QSelect
Interactive Autocompletion Example:
<template>
<div class="q-pa-md">
<div class="q-gutter-md row">
<q-select
filled
:model-value="dataModel"
use-input
hide-selected
fill-input
input-debounce="0"
:options="dataOptions"
@filter="performFiltering"
@input-value="setSelectedValue"
hint="Interactive Text Autocompletion"
style="width: 250px; padding-bottom: 32px"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey">
No matches found
</q-item-section>
</q-item>
</template>
</q-select>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
const suggestions = [
'Google', 'Facebook', 'Twitter', 'Apple', 'Oracle'
].reduce((acc, option) => {
for (let i = 1; i <= 5; i++) {
acc.push(option + ' ' + i)
}
return acc
}, [])
export default {
setup () {
const dataModel = ref(null)
const dataOptions = ref(suggestions)
return {
dataModel,
dataOptions,
performFiltering (value, update, abort) {
update(() => {
const key = value.toLocaleLowerCase()
dataOptions.value = suggestions.filter(item => item.toLocaleLowerCase().indexOf(key) > -1)
})
},
setSelectedValue (value) {
dataModel.value = value
}
}
}
}
</script>
For scenarios where Lazy filtering is needed, like fetching suggestions from a REST API:
QSelect
Delayed Filtering Sample:
<template>
<div class="q-pa-md">
<div class="q-gutter-md row">
<q-select
filled
v-model="contentModel"
use-input
hide-selected
fill-input
input-debounce="0"
label="Delayed Filter"
:options="apiOptions"
@filter="fetchDataSuggestions"
@filter-abort="abortFetching"
style="width: 250px"
hint="Utilizing hide-selected and fill-input features"
>
<template v-slot:no-option>
<q-item>
<q-item-section class="text-grey">
No content available
</q-item-section>
</q-item>
</template>
</q-select>
</div>
</div>
</template>
<script>
import { ref } from 'vue'
const apiOptions = [
'Google', 'Facebook', 'Twitter', 'Apple', 'Oracle'
]
export default {
setup () {
const contentModel = ref(null)
return {
contentModel,
apiOptions,
fetchDataSuggestions (query, update, abort) {
// Use abort() if data retrieval fails
setTimeout(() => {
update(() => {
if (query === '') {
apiOptions = apiOptions
}
else {
const keyword = query.toLowerCase()
apiOptions = apiOptions.filter(item => item.toLowerCase().includes(keyword))
}
})
}, 1500)
},
abortFetching () {
// console.log('Delayed fetch aborted')
}
}
}
}
</script>