引言
无知的我一直以为类似这些请求都可以用ajax解决…但是现在才知道ajax仅局限于同域下发送异步请求,至于什么是jsonp请求以及同源政策百度说的很清楚。
页面效果:
PS:界面js效果包括键盘上下、文本框聚集失焦,如有补充欢迎大家提建议。
CSS 代码
*{
font-family:微软雅黑;
margin:0px;
padding:0px;
}
.box{
width:610px;
position:absolute;
left:50%;
top:50%;
margin-left: -280px;
margin-top: -200px;
}
.logo img{
width:260px;
margin-left:120px;
margin-bottom:20px;
}
.searchBox input{
width:500px;
height:30px;
}
.searchBox button{
height:34px;
padding-left:20px;
padding-right:15px;
background:#3385ff;;
margin-left:-5px;
border:0px;
/* border-radius:5px; */
color:#fff;
letter-spacing:1px;
}
.listBox{
/* background:#f0f; */
width:505px;
/* height:300px; */
margin-top:-2px;
position:absolute;
top:50%;
left:50%;
margin-left:-282px;
margin-top:-18px;
/* outline-color:#272826; */
}
.active{
box-shadow: 0 2px 6px 0 rgba(0,0,0,0.1);
}
.itemActive{
background:#eee;
}
.listBox .item{
height:36px;
/* background:#aaf; */
padding-left:8px;
line-height:36px;
}
.listBox .item:hover{
background:#eee;
}
[v-cloak]{
display:none;
}
.icon{
width:18px;
height:16px;
position:absolute;
left:50%;
background:url('https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/static/protocol/https/soutu/img/camera_new_5606e8f.png') no-repeat;
left:476px;
bottom:8px;
}
html 代码
<div id="app">
<div class="box">
<div class="logo">
<img src="https://www.baidu.com/img/bd_logo1.png" alt="" />
</div>
<div class="searchBox">
<input type="text" @blur='hidden()' @focus='display()' name="" v-model='keywords' @keyup='search($event)' @keydown.down='nextItem()' @keydown.up.prevent='priorItem()' />
<div class='icon'></div>
<button >百度一下</button>
</div>
</div>
<div class="listBox" :class='{active:list[0] != null}' >
<div class="item" v-for='(vo, index) in list' :class='{itemActive:currentIndex == index}' v-cloak>{{vo}}</div>
</div>
</div>
JS 代码
window.onload = function(){
var vm = new Vue({
el:'#app',
data:{
keywords:'',
list:[],
tempList:[],
currentIndex:-1
},
methods:{
search(e){
if(e.keyCode == 38 || e.keyCode == 40){
return;
}
this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
{
params:{
wd:this.keywords
}
,
jsonp:'cb'//callback的名称
}
).then(function(res){
console.log(res.body);
this.list = res.body.s;
this.tempList = this.list;
},function(res){
// console.log(res.status);
})
},
hidden(){
this.list = [];
},
display(){
if(this.keywords != ''){
this.list = this.tempList;
}
},
nextItem(){
this.currentIndex++;
// console.log(this.currentIndex);
if(this.currentIndex == this.list.length){
this.currentIndex = -1;
}
},
priorItem(){
this.currentIndex--;
// console.log(this.currentIndex);
if(this.currentIndex == -1){
this.currentIndex = this.list.length;
}
}
}
})
}