Check out this sample code:
https://jsfiddle.net/JLLMNCHR/09qtwbL6/96/
The following is the HTML code:
<div id="app">
<button type="button" v-on:click="displayVal()">Button1</button>
<autocomplete v-model="nombre" :items="[ 'Apple', 'Banana', 'Orange', 'Mango', 'Pear', 'Peach', 'Grape', 'Tangerine', 'Pineapple']" />
<button type="button" v-on:click="displayVal()">Button2</button>
</div>
<script type="text/x-template" id="autocomplete">
<div class="autocomplete">
<input type="text" @input="onChange" v-model="search" @keyup.down="onArrowDown" @keyup.up="onArrowUp" @keyup.enter="onEnter" />
<ul id="autocomplete-results" v-show="isOpen" class="autocomplete-results">
<li class="loading" v-if="isLoading">
Loading results...
</li>
<li v-else v-for="(result, i) in results" :key="i" @click="setResult(result)" class="autocomplete-result" :class="{ 'is-active': i === arrowCounter }">
{{ result }}
</li>
</ul>
</div>
</script>
This is the JS section:
const Autocomplete = {
name: "autocomplete",
template: "#autocomplete",
props: {
items: {
type: Array,
required: false,
default: () => []
},
isAsync: {
type: Boolean,
required: false,
default: false
}
},
data() {
return {
isOpen: false,
results: [],
search: "",
isLoading: false,
arrowCounter: 0
};
},
// More methods and functions go here...
};
The CSS part looks like this:
#app {
font-family: "Avenir", Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
color: #2c3e50;
margin-top: 60px;
}
.autocomplete {
position: relative;
width: 130px;
}
// Styling for autocomplete and its results
How can I make sure that displayVal shows the selected value from autocomplete or the user input if it's not in the list? Also, how do I go about displaying Button2?