akkoma-fe/src/components/autosuggest/autosuggest.js

53 lines
1.0 KiB
JavaScript
Raw Normal View History

const debounceMilliseconds = 500
2019-04-02 10:12:31 +00:00
export default {
props: {
query: { // function to query results and return a promise
type: Function,
required: true
},
filter: { // function to filter results in real time
type: Function
2019-04-02 19:43:41 +00:00
},
placeholder: {
type: String,
default: 'Search...'
}
},
2019-04-02 10:12:31 +00:00
data () {
return {
term: '',
2019-04-02 17:18:36 +00:00
timeout: null,
results: [],
2019-04-02 17:18:36 +00:00
resultsVisible: false
}
},
computed: {
filtered () {
return this.filter ? this.filter(this.results) : this.results
}
},
watch: {
term (val) {
this.fetchResults(val)
2019-04-02 10:12:31 +00:00
}
},
methods: {
fetchResults (term) {
2019-04-02 10:12:31 +00:00
clearTimeout(this.timeout)
this.timeout = setTimeout(() => {
this.results = []
if (term) {
this.query(term).then((results) => { this.results = results })
}
}, debounceMilliseconds)
2019-04-02 17:18:36 +00:00
},
onInputClick () {
this.resultsVisible = true
},
onClickOutside () {
this.resultsVisible = false
2019-04-02 10:12:31 +00:00
}
}
}