-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsearch.js
66 lines (63 loc) · 1.36 KB
/
search.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
var SearchInput = {
template: `
<input type="text" placeholder="search..." class="search-input" v-model="keyword" @keyup="onInput">
`,
data () {
return {
keyword: ''
}
},
methods: {
onInput () {
this.$emit('search', this.keyword)
}
}
}
var SearchResults = {
template: `
<div>
<ul v-if="posts.length > 0" class="search-results">
<li v-for="post in posts" class="search-results-item">
<a :href="post.url">{{post.title}}</a>
</li>
</ul>
<span v-if="posts.length === 0 && keyword !== ''" class="not-found">Nothing's found</span>
</div>
`,
props: ['posts', 'keyword']
}
Vue.component('search', {
components: {
SearchInput,
SearchResults
},
template: `
<div>
<search-input @search="results"></search-input>
<search-results :posts=posts :keyword=keyword></search-results>
</div>
`,
data () {
return {
posts: [],
keyword: ''
}
},
methods: {
results (keyword) {
this.keyword = keyword
if (keyword === '') {
return this.posts = []
}
$.get('/posts.json', keyword).done((data) => {
var results = _.filter(data, (post) => {
return post.title.toLowerCase().indexOf(keyword.toLowerCase()) !== -1
})
this.posts = results
})
}
}
})
new Vue({
el: '#search'
})