在我们学习ajax的时候一定要做的例子就是下拉菜单了吧?为什么?因为当你输入一个值的时候下面的div里面会无刷新的去加入数据,当时的实现也是挺难的,反正比下面的vue实现难。。。下面我们来看看vue(我觉得vue的出现就是good啊)
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<head>
<title>百度搜索</title>
<style>
.gray{
background: darkgray;
}
</style>
</head>
<script src="vue1.X.js"></script>
<script src="vue-resource.js"></script>
<body>
<div id="box">
下面我们是为input加入事件,keyup事件就是当你搜索的时候随着你抬起来键盘,下面的li中加入值。下面我们还添加了keydown事件,能用到keydown事件的地方最好用keydown
我在methods里面写了changedown和changeup两个方法去控制当键盘上下按动时那个背景颜色跟着变化,用.prevent去阻止键盘默认事件的发生
<input type="text" name="" @keyup="get($event)" v-model="its" @keydown.down.prevent="changedown()" @keydown.up.prevent="changeup()">
<ul>
这个位置看版本吧,$index我这里是用不了,就采取了它的替代方法
<li v-for="(index,value) in mydata" :class="{gray:index==nowIndex}">
{{value}}
</li>
<p v-show="mydata.length==0">暂无数据...</p>
</ul>
</div>
<script type="text/javascript">
new Vue({
el: '#box',
data: {
mydata:[],
its:'',
nowIndex:-1
},
methods: {
get: function (ev) {
当回车的时候可以搜索输入框中的值
if(ev.keyCode==13){
这个接口去network里面找,想做谁的都行
window.open('https://sp0.baidu.com/s?wd='+this.its)
}
if(ev.keyCode==38||ev.keyCode==40){
return;
}
上面的vue-resource就是用来为这里提供服务的,交互。。。
this.$http.jsonp('https:' +
'//sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',
{wd: this.its},
{jsonp: 'cb'这里面默认的值是callback,不过看看百度的格式里面的是cb,你修改成cb就可以}).then(function (res) {
this.mydata=res.data.s这里之前我想用push的结果全都整成一行了,估计要循环,太费劲了
}, function (req) {
alert(req.status)失败之后要做的事情
})
},
changedown:function(){
this.nowIndex++;
if(this.nowIndex==this.mydata.length){
this.nowIndex=-1;
}
this.its=this.mydata[this.nowIndex]
},
changeup:function(){
this.nowIndex--;
if(this.nowIndex==-2){
this.nowIndex=this.mydata.length-1;
}
this.its=this.mydata[this.nowIndex]
}
}
})
这下面是我找的接口
// https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&cb=jshow
// https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=a&sugmode=2&json=1&p=3&sid=1448_21116_17001_25227_25178_22074&req=2&bs=a&csor=1&cb=jQuery110202944792992942089_1513421964350&_=1513421964352
// https://sp1.baidu.com/5b11fzupBgM18t7jm9iCKT-xh_/sensearch?wd=
</script>
</body>
</html>
越来越觉得vue很好,比angularjs简单,可能是因为中国人维护的吧