Vue去哪儿项目&搜索功能实现


搜索功能实现

效果图

src\pages\city\components\Search.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
<div class="search-content" ref="search" v-show="keyword">
<ul>
<li
class="search-item border-bottom"
v-for="item of list"
:key="item.id"
>
{{ item.name }}
</li>
<li class="search-item border-bottom" v-show="hasNoData">
没有找到匹配数据
</li>
</ul>
</div>

.search-content
z-index:1
overflow :hidden
position:absolute
top: 1.58rem
right:0
left:0
bottom:0
background:#eee
.search-item
line-height :.62rem
padding-left :.2rem
color:#666
background:#fff
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
<template>
<div>
<div class="search">
<input
v-model="keyword"
class="search-input"
type="text"
placeholder="输入城市名或拼音"
/>
<div class="search-content" ref="search" v-show="keyword">
<ul>
<li
class="search-item border-bottom"
v-for="item of list"
:key="item.id"
>
{{ item.name }}
</li>
<li class="search-item border-bottom" v-show="hasNoData">
没有找到匹配数据
</li>
</ul>
</div>
</div>
</div>
</template>
<script>
import Bscroll from "better-scroll";
export default {
name: "CitySearch",
props: {
cities: Object
},
data() {
return {
keyword: "",
list: [],
timer: null
};
},
computed: {
hasNoData() {
return !this.list.length;
}
},
watch: {
keyword() {
if (this.timer) {
clearTimeout(this.timer);
}
if (!this.keyword) {
this.list = [];
return;
}
//防抖节流函数
this.timer = setTimeout(() => {
const result = [];
for (let i in this.cities) {
this.cities[i].forEach(value => {
if (
value.spell.indexOf(this.keyword) > -1 ||
value.name.indexOf(this.keyword) > -1
) {
result.push(value);
}
});
}
this.list = result;
}, 100);
}
},
mounted() {
this.scroll = new Bscroll(this.$refs.search);
}
};
</script>

【性能优化–节流】
函数节流:通过设定一个时间周期,只要在这个周期内函数就不执行。

【防抖】
写一个侦听器 watch,在里边监听 keyword 的改变,考虑到性能优化,使用防抖的方式来实现,先在 data 中定义一个 timer 定时器,默认值为 null,然后在监听 keyword 的方法中,判断,当 timer 不为 null 时,清除这个定时器。下面写这个定时器的方法,当延时 100ms 的时候,箭头函数会被执行。