Vue實現(xiàn)百度下拉提示搜索功能
一、前期準備
網(wǎng)上大神已經(jīng)做過這個功能https://github.com/lavyun/vue-demo-search 這自己僅實現(xiàn)搜索功能
為了使用百度實現(xiàn)搜索功能,首先搞清楚下拉數(shù)據(jù)和搜索功能的數(shù)據(jù)接口
01、提示數(shù)據(jù)獲取地址
打開百度官網(wǎng)打開開發(fā)者調(diào)試工具,選中network一項,然后我們在搜索框輸入'a',將會network發(fā)送的請求,這個就是提示數(shù)據(jù)的數(shù)據(jù)獲取地址

提示數(shù)據(jù)獲取地址.png
然后簡化一下:
其中“wd=”后接搜索的關(guān)鍵字,“cb=”后接回調(diào)函數(shù)

輸入a時,請求的提示數(shù)據(jù)
02:搜索功能實現(xiàn)地址
在輸入框中輸入“a”之后,點擊搜索按鈕之后,地址欄中地址就是實現(xiàn)搜索功能的地址

搜索地址.png
搜索地址簡化前后對比,是不是看起來很舒服了O(∩_∩)O

簡化地址.png
我們使用簡化之后的地址,搜索關(guān)鍵字“s‘'測試一下

測試.png
二、代碼實現(xiàn)
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="請輸入想要搜索關(guān)鍵字" 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">(*^__^*)暫時沒有數(shù)據(jù)</h2></p>
</div>
get方法實現(xiàn)獲取下拉數(shù)據(jù)和搜索功能,輸入keyword之后,調(diào)用get方法使用jsonp獲取提示數(shù)據(jù),然后賦值給myData,然后使用v-for遍歷提示數(shù)據(jù)

提示數(shù)據(jù).png
然后selectDown和selectUp實現(xiàn)上下選中數(shù)據(jù),當按下回車鍵時,實現(xiàn)搜索
完整代碼:https://github.com/yanqiangmiffy/baidu-search
三、實現(xiàn)效果

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于vue利用postcss-pxtorem進行移動端適配的問題
這篇文章主要介紹了關(guān)于vue利用postcss-pxtorem進行移動端適配的問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
vue將后臺數(shù)據(jù)時間戳轉(zhuǎn)換成日期格式
這篇文章主要為大家詳細介紹了vue將后臺數(shù)據(jù)時間戳轉(zhuǎn)換成日期格式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-07-07
Vue.js結(jié)合bootstrap實現(xiàn)分頁控件
這篇文章主要為大家詳細介紹了Vue.js 合bootstrap實現(xiàn)分頁控件的相關(guān)資料,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03

