用vue实现搜索功能

1、input搜索的内容显示在我们定义的区块里,我们要把input框里面输入的值要和数据做个绑定,要用到双向绑定

data(){
return{
keyword:’’
}
}
另外还要接收父组件里面的值,用:绑定,子组件用props接收

2、我们还要定义一个属性
data(){
return{
keyword:’’,
list:[]
timer:null //用于节流属性
}
}
用watch监听变化
watch:{
keyword(){
//用到了节流函数 进行判断这个值(数据是否存在),监听的是keyword值的变化,
if(this.timer){
clearTimeout(this.timer)
}
if(!this.keyword){//如果搜索的内容不存在,则返回一个空数组
this.list=[]
return
}
this.timer = setTimeout(()=>{
const result = []
for (let i in this.cities){ //cities就是用props接收的值
this.cities[i].forEach((value)=>{
//判断是否存在
if(value.spell.indexOf(this.keyword)>-1||
value.name.indexOf(this.keyword)>-1{
//追加到result中
result.push(value)
}
})
this.list = result
},100)
}

html中也要进行循环,这个结构就是我们搜索出来的内容结构

发布了9 篇原创文章 · 获赞 6 · 访问量 42

猜你喜欢

转载自blog.csdn.net/weixin_46137478/article/details/104720410