/
main.js
104 lines (86 loc) · 1.82 KB
/
main.js
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
import Vue from 'vue'
export default {
data () {
return {
items: [],
query: '',
current: -1,
loading: false
}
},
ready () {
if (! this.$http) {
this.warn('`vue-resource` plugin')
}
if (! this.src) {
this.warn('`src` property')
}
if (! this.onHit) {
this.warn('`onHit` method')
}
},
computed: {
hasItems () {
return this.items.length > 0
},
isEmpty () {
return !this.query
},
isDirty () {
return !!this.query
}
},
methods: {
warn (msg) {
Vue.util.warn('Typeahead requires the ' + msg)
},
update () {
if (! this.query) {
this.reset()
return
}
this.loading = true
this.$http.get(this.src, Object.assign({q:this.query}, this.data))
.then(function (response) {
if (this.query) {
var data = response.data
data = this.prepareResponseData ? this.prepareResponseData(data) : data
this.items = !!this.limit ? data.slice(0, this.limit) : data
this.current = -1
this.loading = false
}
}.bind(this))
},
reset () {
this.items = []
this.query = ''
this.loading = false
},
setActive (index) {
this.current = index
},
activeClass (index) {
return {
active: this.current == index
}
},
hit () {
if (this.current === -1) return
this.onHit(this.items[this.current])
},
up () {
if (this.current > 0)
this.current--
else if (this.current == -1)
this.current = this.items.length - 1
else
this.current = -1
},
down () {
if (this.current < this.items.length-1)
this.current++
else
this.current = -1
}
}
}