vue-vue-resource跨域请求实例(根据用户关键词获取百度搜索列表)

一、需求分析

开发百度搜索功能。技术要求:使用vue-resource发送JSONP请求,实现跨域请求百度搜索列表的功能。

 

二、代码实现

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4   <meta charset="UTF-8">
 5   <title>百度搜索列表</title>
 6 <!--  引入vue-->
 7   <script src="../js/vue.js"></script>
 8   <!-- 引入vue-resource -->
 9   <script src="../js/vue-resource.min.js"></script>
10   <style>
11     .current{
12       background-color: #f2f2f2;
13       color: blue;
14     }
15     .ulStyle{
16       width: 300px;
17       border: 1px solid #c3c3c3;
18       list-style: none;
19       margin: 0;
20       padding: 10px 0;
21     }
22   </style>
23   <script>
24     window.onload=function(){
25       new Vue({
26         el:'#hello',
27         //data用来存储数据
28         data:{
29           keyword:'',
30           myData:[],
31           now:-1 //当前鼠标选中项的索引
32         },
33         //methods用来存储方法
34         methods:{
35           //获取搜索结果并显示在文本框
36           getData(e){
37             //如果方向键为上或下,则不发送请求
38             if(e.keyCode==38||e.keyCode==40)
39               return;
40             // https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&json=1&p=3&sid=1420_21118_17001_21931_23632_22072&req=2&csor=1&cb=jQuery110208075694879886905_1498805938134&_=1498805938138
41             this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
42               params:{
43                 'wd':this.keyword
44               },
45               jsonp:'cb'
46             }).then(resp=>{
47               console.log('获取百度搜索列表成功',resp.body.s)
48               this.myData=resp.body.s
49             }).catch(err=>{
50               console.log('获取百度搜索列表失败',err)
51             })
52           },
53 
54           //键盘按down的时候
55           changeDown(){
56             this.now++;
57             this.keyword=this.myData[this.now];
58             if(this.now==this.myData.length){
59               this.now=-1;
60             }
61           },
62 
63           //键盘按up的时候
64           changeUp(){
65             this.now--;
66             this.keyword=this.myData[this.now];
67             if(this.now==-2){
68               this.now=this.myData.length-1;
69               this.keyword=this.myData[this.now];
70             }
71           },
72 
73         },
74       })
75     }
76   </script>
77 </head>
78 <body>
79 <div id="hello">
80   <input type="text" v-model='keyword' @keyup='getData($event)' @keydown.down="changeDown" @keydown.up.prevent='changeUp'>
81   <ul class="ulStyle" v-show='myData.length>0'>
82     <li v-for='(value,index) in myData' :class='{current:index==now}'>{{value}}</li>
83   </ul>
84   <p v-show="myData.length==0">暂无搜索结果</p>
85 </div>
86 </body>
87 </html>

 

三、效果展示

 

 

posted @ 2021-08-26 10:34  AnnLing  阅读(162)  评论(0)    收藏  举报