-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathAutocomplete.vue
103 lines (86 loc) · 2.13 KB
/
Autocomplete.vue
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
<template>
<div style="position:relative" v-bind:class="{'open':openSuggestion}">
<input class="form-control" type="text" :value="value" @input="updateValue($event.target.value)"
@keydown.enter = 'enter'
@keydown.down = 'down'
@keydown.up = 'up'
>
<ul class="dropdown-menu" style="width:100%">
<li v-for="(suggestion, index) in matches" :key="suggestion.id"
v-bind:class="{'active': isActive(index)}"
@click="suggestionClick(index)"
>
<a href="#">{{ suggestion.city }} <small>{{ suggestion.state }}</small>
</a>
</li>
</ul>
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
required: true
},
suggestions: {
type: Array,
required: true
}
},
data () {
return {
open: false,
current: 0
}
},
computed: {
// Filtering the suggestion based on the input
matches () {
return this.suggestions.filter((obj) => {
return obj.city.indexOf(this.value) >= 0
})
},
openSuggestion () {
return this.selection !== '' &&
this.matches.length !== 0 &&
this.open === true
}
},
methods: {
updateValue (value) {
if (this.open === false) {
this.open = true
this.current = 0
}
this.$emit('input', value)
},
// When enter pressed on the input
enter () {
this.$emit('input', this.matches[this.current].city)
this.open = false
},
// When up pressed while suggestions are open
up () {
if (this.current > 0) {
this.current--
}
},
// When up pressed while suggestions are open
down () {
if (this.current < this.matches.length - 1) {
this.current++
}
},
// For highlighting element
isActive (index) {
return index === this.current
},
// When one of the suggestion is clicked
suggestionClick (index) {
this.$emit('input', this.matches[index].city)
this.open = false
}
}
}
</script>