vue 中应用节流函数
<template>
<div>
<input type="search" placeholder="输入" v-model="key" />
<ul>
<li v-for="item in data" :key="item.id">
{{item.name}}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
// 输入的字符
key: '',
// 搜索到的数据
data: [],
timer: null,
list: [
{
"id": 56,
"spell": "aba",
"name": "阿坝"
}, {
"id": 57,
"spell": "akesu",
"name": "阿克苏"
}, {
"id": 58,
"spell": "alashanmeng",
"name": "阿拉善盟"
}, {
"id": 59,
"spell": "aletai",
"name": "阿勒泰"
}, {
"id": 60,
"spell": "ali",
"name": "阿里"
}, {
"id": 61,
"spell": "ankang",
"name": "安康"
}, {
"id": 62,
"spell": "anqing",
"name": "安庆"
}, {
"id": 63,
"spell": "anshan",
"name": "鞍山"
}, {
"id": 64,
"spell": "anshun",
"name": "安顺"
}, {
"id": 65,
"spell": "anyang",
"name": "安阳"
}, {
"id": 338,
"spell": "acheng",
"name": "阿城"
}, {
"id": 339,
"spell": "anfu",
"name": "安福"
}, {
"id": 340,
"spell": "anji",
"name": "安吉"
}, {
"id": 341,
"spell": "anning",
"name": "安宁"
}, {
"id": 342,
"spell": "anqiu",
"name": "安丘"
}, {
"id": 343,
"spell": "anxi",
"name": "安溪"
}, {
"id": 344,
"spell": "anyi",
"name": "安义"
}, {
"id": 345,
"spell": "anyuan",
"name": "安远"
},
{
"id": 1,
"spell": "beijing",
"name": "北京"
}, {
"id": 66,
"spell": "baicheng",
"name": "白城"
}, {
"id": 67,
"spell": "baise",
"name": "百色"
}, {
"id": 68,
"spell": "baishan",
"name": "白山"
}, {
"id": 69,
"spell": "baiyin",
"name": "白银"
}, {
"id": 70,
"spell": "bangbu",
"name": "蚌埠"
}, {
"id": 71,
"spell": "baoding",
"name": "保定"
}
]
}
},
mounted() {
// this.get()
},
methods: {
get() {
this.list.forEach(item=>{
console.log(item.name);
})
}
},
watch:{
key() {
if(this.timer){
console.log(this.key);
clearTimeout(this.timer)
}
// 当未输入值得时候,清空data
if (!this.key) {
return this.data = []
}
this.timer = setTimeout(() => {
const searchList = []
this.list.forEach(item=>{
if(item.name.indexOf(this.key) > -1 ||
item.spell.indexOf(this.key) > -1){
searchList.push(item)
}
})
this.data = searchList
}, 100)
},
}
}
</script>
<style lang="stylus" scoped>
input {
border: 1px solid red;
}
</style>