JSFiddle - React, Tailwind, and code Playground
by Darren Jennings
HTML
<script src="https://unpkg.com/[email protected]/dist/vue-autosuggest.js"></script>
<div id="app">
<pre v-if="selected">You have selected: '{{selected}}'</pre>
<input type="text">
{{query}}
<vue-autosuggest
v-model="query"
@input="onInputChange"
@selected="onSelected"
@blur="onBlur"
@focus="onFocus"
:suggestions="filteredOptions"
:limit="10"
:input-props="inputProps"
:should-render-suggestions="(size, loading) => size >= 0 && !loading && !closed">
</vue-autosuggest>
<input type="text">
</div>
CSS
body {
max-width: 800px;
padding: 20px;
margin-left: auto !important;
margin-right: auto !important;
font-family: monospace;
}
#autosuggest__input {
outline: none;
position: relative;
display: block;
font-family: monospace;
font-size: 20px;
border: 1px solid #616161;
padding: 10px;
width: 100%;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
}
#autosuggest__input.autosuggest__input-open {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.autosuggest__results-container {
position: relative;
width: 100%;
}
.autosuggest__results {
font-weight: 300;
margin: 0;
position: absolute;
z-index: 10000001;
width: 100%;
border: 1px solid #e0e0e0;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
background: white;
padding: 0px;
overflow: scroll;
max-height: 200px;
}
.autosuggest__results ul {
list-style: none;
padding-left: 0;
margin: 0;
}
.autosuggest__results .autosuggest__results-item {
cursor: pointer;
padding: 15px;
}
.autosuggest__results .autosuggest__results-item:active,
.autosuggest__results .autosuggest__results-item:hover,
.autosuggest__results .autosuggest__results-item:focus,
.autosuggest__results .autosuggest__results-item.autosuggest__results-item--highlighted {
background-color: rgba(0,0,0,0.06);
}
JavaScript
new Vue({
data() {
return {
selected: '',
query: '',
options: [{
data: ['Frodo', 'Samwise', 'Gandalf', 'Galadriel', 'Faramir', 'Éowyn', 'Peregrine Took', 'Boromir', 'Legolas', 'Gimli', 'Gollum', 'Beren', 'Saruman', 'Sauron', 'Théoden']
}],
inputProps: {
id: "autosuggest__input",
placeholder: "Type 'e'"
},
limit: 10,
closed: false
};
},
computed: {
filteredOptions() {
const limit = this.limit
return [{
data: this.options[0].data.filter(item => {
return item.toLowerCase().indexOf(this.query.toLowerCase()) > -1;
}).slice(0, limit)
}]
}
},
methods: {
onSelected(option) {
this.selected = option.item;
},
onInputChange(text) {
if (text === '' || text === undefined) {
return;
}
/* Full control over filtering. Maybe fetch from API?! Up to you!!! */
},
onBlur (e) {
if(e.relatedTarget && e.relatedTarget.tagName === 'INPUT') {
this.closed = true
}
},
onFocus(e) {
this.closed = false
}
}
}).$mount('#app')