美文网首页
基于Vue.js 实现百度搜索框效果

基于Vue.js 实现百度搜索框效果

作者: 李亚_45be | 来源:发表于2020-04-02 20:04 被阅读0次
    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遍历提示数据
然后selectDown和selectUp实现上下选中数据,当按下回车键时,实现搜索

相关文章

网友评论

      本文标题:基于Vue.js 实现百度搜索框效果

      本文链接:https://www.haomeiwen.com/subject/nzefphtx.html