1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
| <script>
import axios from 'axios';
export default {
name: 'autocomplete',
props: {
isAsync: {
type: Boolean,
required: false,
default: false,
},
},
data() {
return {
items: [],
isOpen: false,
results: [],
search: '',
isLoading: false,
arrowCounter: 0,
};
},
methods: {
onChange() {
// Let's warn the parent that a change was made
this.$emit('input', this);
// Is the data given by an outside ajax request?
if (this.isAsync) {
this.filterResults();
this.isLoading = true;
} else {
// Let's our flat array
this.filterResults();
this.isOpen = true;
}
},
filterResults() {
// first uncapitalize all the things
this.results = this.items.filter((item) => {
return item.toLowerCase().indexOf(this.search.toLowerCase()) > -1;
});
},
setResult(result) {
this.search = result;
this.isOpen = false;
},
onArrowDown(evt) {
if (this.arrowCounter < this.results.length) {
this.arrowCounter = this.arrowCounter + 1;
}
},
onArrowUp() {
if (this.arrowCounter > 0) {
this.arrowCounter = this.arrowCounter -1;
}
},
onEnter() {
this.search = this.results[this.arrowCounter];
this.isOpen = false;
this.arrowCounter = -1;
},
handleClickOutside(evt) {
if (!this.$el.contains(evt.target)) {
this.isOpen = false;
this.arrowCounter = -1;
}
}
},
watch: {
items: function (val, oldValue) {
// actually compare them
if (val.length !== oldValue.length) {
this.results = val;
this.isLoading = false;
}
},
},
mounted() {
document.addEventListener('click', this.handleClickOutside)
axios.get(`http://jsonplaceholder.typicode.com/posts`)
.then(function(response){
for (var i = 0; i < response.data.length; i++) {
console.log(this);
//this.items.push(response.data[i].title)
}
})
},
destroyed() {
document.removeEventListener('click', this.handleClickOutside)
}
};
</script>
<template>
<div id="fake-input-block" class="autocomplete" >
<input
id="fake-game-input"
type="text"
@input="onChange"
v-model="search"
@keydown.down="onArrowDown"
@keydown.up="onArrowUp"
@keydown.enter="onEnter"
class="form-control"
/>
<span>
<a id="add-game" href="#" class="white" >Ajouter</a>
</span>
<ul
id="autocomplete-results"
v-show="isOpen"
class="autocomplete-results"
style="list-style-type: none;
background: #FFFFFF; color: #222222;"
>
<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>
</template> |
Partager