通过vue的jsonp实现百度下拉菜单的请求,vue的版本是2.9.2
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <script src="vue.min.js"></script> 7 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.min.js"></script> 8 <style> 9 .gray { 10 background-color: #ccc; 11 } 12 </style> 13 <script> 14 window.onload = function () { 15 new Vue({ 16 el: ‘#box‘, 17 data: { 18 myData: [], //搜索下拉数据列表 19 t1: ‘‘, //输入框里的值 20 now: -1 //输入框里面的值得索引,0位列表第一项 21 }, 22 methods: { 23 get: function (ev) { 24 if(ev.keyCode==38 || ev.keyCode==40){ //当按照上下键的时候停止搜索 25 return 26 } 27 if(ev.keyCode==13){ 28 window.open(‘https://www.baidu.com/s?wd=‘+this.t1) //打开百度搜索 29 } 30 this.$http.jsonp(‘https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su‘, { 31 params: { 32 wd: this.t1 // 输入的关键词 33 }, 34 jsonp: ‘cb‘ //callback函数的名称 35 }).then(function (res) { 36 this.myData=res.data.s; 37 console.log(this.myData) 38 }, function (err) { 39 console.log(err.status); 40 }); 41 }, 42 changeDown: function () { //向下选择 43 this.now++; 44 if (this.now == this.myData.length) { //判断是否超出列表长度 45 this.now = -1; 46 } 47 this.t1 = this.myData[this.now]; //改变输入框的值 48 }, 49 changeUp: function () { //向上选择 50 this.now--; 51 if (this.now == -2) { 52 this.now = this.myData.length - 1; 53 } 54 this.t1 = this.myData[this.now]; 55 }, 56 dataLink: function (index) { //鼠标点击跳转 57 this.t1 = this.myData[index]; 58 this.now = index; 59 window.open(‘https://www.baidu.com/s?wd=‘ + this.t1); 60 this.t1 = ‘‘ 61 } 62 } 63 }) 64 } 65 </script> 66 </head> 67 <body> 68 <div id="box"> 69 <input type="text" v-model="t1" @keyup="get($event)" @keydown.down="changeDown()" @keydown.up.prevent="changeUp()"> 70 <ul> 71 <li v-for="(value,index) in myData" :class="{gray:index==now}"> 72 {{ value }} 73 </li> 74 </ul> 75 <p v-show="myData.length==0">暂无数据...</p> 76 </div> 77 78 </body> 79 </html>