<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>仿百度搜索框</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<style>
.
bg{
background:
#cccccc;
}
</style>
<script src="vue.js"></script>
<script src="vue-resource.js"></script>
</head>
<body>
<div>
<input type="text" placeholder='请输入搜索的内容。。。' v-model='info' @keyup='search($event)' @keydown.down='change()' @keydown.up.provent='up()'>
<ul>
<li v-for='v in myData' :class='{bg:$index==index}'>{{v}}</li>
</ul>
<h1 v-show='myData.length==0'>暂无数据。。。</h1>
</div>
<script>
var myDemo= new Vue({
el:'body',
data:{
myData:[],
//储存搜索到的内容
info:'',
//input框里输入的内容
index:-1 //索引 实现上下选择
},
methods:{
search:function (
e) {
// 当按上下键时返回
if(
e.
keyCode==38||e.
keyCode==40)
return;
// 按回车时搜索
if(
e.
keyCode==13){
// 新的页面打开
window.
open(
'https://www.baidu.com/s?wd='+this.
info);
this.
info='';
}
// 跨域调用百度搜索接口
this.
$http.
jsonp(
'https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su',{
wd:this.
info
},{
jsonp:'cb' //必须要有jsonp 后面参数根据实际需求写
}).
then(
function (
data) {
//成功是返回的内容
this.
myData=data.data.s;
//储存返回的内容
},
function () {
})
},
// 按下键往下选择
change:function () {
this.
index++;
this.
info=this.
myData[
this.
index];
//输入框显示选择的内容
if(
this.
index==this.
myData.
length)
this.
index=-1;
//当选到最后一个时索引变为-1
},
// 按上键往上选择
up:function () {
this.
index--;
this.
info=this.
myData[
this.
index];
if(
this.
index==-1)
this.
index=this.
myData.
length-1;
}
}
}
)
</script>
</body>
</html>
转载请注明原文地址: https://www.6miu.com/read-11481.html