Vue实现百度下拉提示搜索功能

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue实现百度下拉提示搜索功能

致Great   2020-05-15 我要评论

一、前期准备

网上大神已经做过这个功能https://github.com/lavyun/vue-demo-search 这自己仅实现搜索功能
为了使用百度实现搜索功能,首先搞清楚下拉数据和搜索功能的数据接口

01、提示数据获取地址

打开百度官网打开开发者调试工具,选中network一项,然后我们在搜索框输入'a',将会network发送的请求,这个就是提示数据的数据获取地址


提示数据获取地址.png

然后简化一下:

复制代码 代码如下:
https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&cb=jQuery110208352732182923484_1497924041050&_=1497924041057#

其中“wd=”后接搜索的关键字,“cb=”后接回调函数


输入a时,请求的提示数据

02:搜索功能实现地址

在输入框中输入“a”之后,点击搜索按钮之后,地址栏中地址就是实现搜索功能的地址


搜索地址.png

搜索地址简化前后对比,是不是看起来很舒服了O(∩_∩)O


简化地址.png

我们使用简化之后的地址,搜索关键字“s‘'测试一下


测试.png

二、代码实现

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遍历提示数据


提示数据.png

然后selectDown和selectUp实现上下选中数据,当按下回车键时,实现搜索
完整代码:https://github.com/yanqiangmiffy/baidu-search

三、实现效果


Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们