参考https://github.com/lavyun/vue-demo-search
一、简化搜索地址
为了使用百度实现搜索功能,首先搞清楚下拉数据和搜索功能的数据接口
01:提示数据获取地址
打开百度官网打开开发者调试工具,选中network一项,然后我们在搜索框输入'a',将会network发送的请求,这个就是提示数据的数据获取地址
![](https://img.haomeiwen.com/i1531909/45b988d94ca4d286.png)
然后简化一下:
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&cb=jQuery110208352732182923484_1497924041050&_=1497924041057#
其中“wd=”后接搜索的关键字,“cb=”后接回调函数
![](https://img.haomeiwen.com/i1531909/3cb90e7c4ffef9d2.png)
02:搜索功能实现地址
在输入框中输入“a”之后,点击搜索按钮之后,地址栏中地址就是实现搜索功能的地址
![](https://img.haomeiwen.com/i1531909/37db51d4036cf03d.png)
搜索地址简化前后对比
![](https://img.haomeiwen.com/i1531909/bcc902855fc93857.png)
我们使用简化之后的地址,搜索关键字“s‘’测试一下
![](https://img.haomeiwen.com/i1531909/58a983674f4963b4.png)
实现效果所用知识
1. 样式:bootstrap
2. 常见:vue-resource.js(ajax库),实现跨域请求
- js代码
new Vue({
el:'#app',
data:{
myData:[],
keyword:'',
now:-1
},
methods:{
get:function (event) {
if(event.keyCode==38||event.keyCode==40)return;
if(event.keyCode==13){
window.open('https://www.baidu.com/s?wd='+this.keyword);
this.keyword=''
}
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
wd:this.keyword
},{
jsonp:'cb'
}).then(function (res) {
this.myData=res.data.s;
},function () {
});
},
selectDown:function () {
this.now++;
if(this.now==this.myData.length)this.now=-1;
this.keyword=this.myData[this.now];
},
selectUp:function () {
this.now--;
if(this.now==-2)this.now=this.myData.length-1;
this.keyword=this.myData[this.now];
}
}
})
- html代码
<div class="container search-container" id="app">
<h1 class="title" >baidu-search</h1>
<input type="text" class="form-control" placeholder="请输入想要搜索关键字" v-model="keyword" @keyup="get($event)" @keydown.down.prevent="selectDown"
@keydown.up.prevent="selectUp">
<ul>
<li class="text-center" v-for="(value,index) in myData"><span class="text-success textprimary" :class="{gray:index==now}">{{value}}</span></li>
</ul>
<p ><h2 v-show="myData.length==0" class="text-warning text-center">暂时无数据</h2></p>
</div>
get方法实现获取下拉数据和搜索功能,输入keyword之后,调用get方法使用jsonp获取提示数据,然后赋值给myData,然后使用v-for遍历提示数据
![](https://img.haomeiwen.com/i16749538/19d4e4de5ba1762b.png)
然后selectDown和selectUp实现上下选中数据,当按下回车键时,实现搜索
三、实现效果
![](https://img.haomeiwen.com/i1531909/54531728545771ad.gif)
完整代码:https://github.com/yanqiangmiffy/baidu-search
网友评论