使用vue-resource提供的jsonp()方法实现跨域请求。此案例模仿实现360搜索引擎的查询效果。
实现效果
源码
使用到的文件(3个): 1.vue.js 2.vue-resource.js (上面两个文件需要自己本机存在才能运行源码,注意导入的路径。如果本地没有,可以使用相关的https://…在线链接引入,官网都有。) 3.360搜索列表.html (如下)
360搜索列表.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
<script src="js/vue-resource.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
window.onload = function(){
new Vue({
el:'div',
data:{
searchTxt:'',
dataList:[],
nowSelected:-1,
text:''
},
methods:{
search(e){
if(e.keyCode==38 || e.keyCode==40){
return ;
}
this.$http.jsonp('https://sug.so.360.cn/suggest',{
params:{
word:this.searchTxt,
}
})
.then(response => {
let arr = response.data.result;
let arr1 = [];
arr.forEach(function(value,index){
arr1.push(value.word);
})
this.dataList = arr1;
this.text = this.searchTxt;
})
.catch(error => {
console.log(error);
})
},
changeDown(){
this.nowSelected++;
this.searchTxt = this.dataList[this.nowSelected];
if(this.nowSelected==this.dataList.length){
this.searchTxt = this.text;
this.nowSelected = -1;
}
},
changeUp(){
this.nowSelected--;
this.searchTxt = this.dataList[this.nowSelected];
if(this.nowSelected<=-1){
this.nowSelected = this.dataList.length;
this.searchTxt = this.text;
}
},
showResult(){
let search = this.searchTxt;
window.open(`https://www.so.com/s?q=${search}`);
}
}
})
}
</script>
<style type="text/css">
ul {
display: block;
list-style-type: disc;
margin-block-start: 0em;
margin-block-end: 0em;
margin-inline-start: 0px;
margin-inline-end: 0px;
padding-inline-start: 0px;
}
ul li{
height:25px;padding: 3px 0px;
}
div div{
float: left;
}
#search{
margin-top: 35px;
line-height: 30px;
width: 300px;
border-radius: 0;
border:2px solid gainsboro;
}
#search:focus{
outline-color: #19b955;
}
#search input{
font-size: 16px;
line-height: 20px;
padding: 4px 0px;
border: none;
outline: none;
}
#searchBtn{
font-size: 15px;
text-align: center;
color:#fff;
margin-top: 35px;
line-height: 30px;
width: 70px;
border-radius: 0;
margin-left: -10px;
background-color: #19b955;
border:1px solid #19b955
}
#searchBtn:active,#searchBtn::after{
border-radius: 0;
outline-color: #19b955;
border:1px solid #19b955
}
.current{
border-radius: 0;
background: #e0e0e1;
}
</style>
</head>
<body>
<div>
<div><img src="https://img2.baidu.com/it/u=2775368996,1002333677&fm=26&fmt=auto" height="100px" ></div>
<div>
<div id="search" > <input type="text" v-model="searchTxt" @keyup="search($event)" @keydown.down="changeDown()" @keydown.up.prevent="changeUp()" @keydown.enter="showResult()"></div>
<input id="searchBtn" type="button" value="搜 索" @click="showResult()">
<ul v-for="(data,index) in dataList" style="list-style: none;">
<li :class="{current:index===nowSelected}" v-show="index<10?true:false" >{{data}}</li>
</ul>
</div>
</div>
</body>
</html>
|