HTML代码:
<!-- 搜索商品页面 -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport"/>
<title>Document</title>
<link rel="stylesheet" href="TB.css" />
</head>
<body>
<div class="search_moduel">
<span class="search_moduel_direction search_moduel_direction2" @click="back()">←</span>
<input type="text" class="msearch_moduel" v-model="search1" @keyup="search($event)" @keydown.down="changeDown()" @keydown.up.prevent="changeUp()"/>
<span class="search_moduel_direction search_moduel_direction1" @click="sure_search()">→</span>
<ul>
<li v-for="(value,index) in myData" v-cloak :class="{gray:index==now}">
{{value}}
</li>
</ul>
<!-- 当输入值为空时,显示 -->
<p v-show='search1.length==0' class="blank_s" v-cloak>请输入搜索内容</p>
</div>
<script src="vue.js"></script>
<script src="node_modules\vue-resource\dist\vue-resource.js"></script>
<script src="TB.js"></script>
</body>
</html>
JS部分:
var search_moduel = new Vue({
el:'.search_moduel',
data:{
myData:[],
search1:'',
now:-1
},
methods:{
search:function(e){
if(e.keyCode==13){
window.open('https://s.taobao.com/search?q='+this.search1);
}
this.$http.jsonp("https://suggest.taobao.com/sug",{
params:{
q:this.search1 //搜索值等于输入的值
}
}).then(resp=>{
//当搜索框里没有值时,清空this.myData的值
if(this.search1==''){
this.myData='';
}else{
var obj = []; //定义一个新数组
for(var i=0;i<res.data.result.length;i++){
//将result中的每一个值放入数组中
obj.push(res.data.result[i][0]);
//将obj数组的值赋给this.myData
this.myData = obj;
// this.myData=res.data.result[i][0];
}
// console.log(this.myData);
}
},response => {
console.log("发送失败"+response.status+","+response.statusText);
}).catch();
},
//按下键,并且搜索框随时更新值
changeDown:function(){
this.now++;
if(this.now==this.myData.length){
this.now=0;
}
this.search1=this.myData[this.now];
},
//按上键,并且搜索框随时更新值
changeUp:function(){
this.now--;
if(this.now==-2){
this.now=this.myData.length-1;
}
this.search1=this.myData[this.now];
},
//点击搜索按钮,跳转至搜索结果页
sure_search:function(){
window.open('https://s.taobao.com/search?q='+this.search1);
},
back:function(){
window.history.back();
}
}
});
附上淘宝的两个接口:
1、搜索提示接口:https://suggest.taobao.com/sug 它使用的是q关键字搜索,也就是说我们输入的值要赋给q
2、搜索结果接口:https://s.taobao.com/search?q=a 其中这个q值时随意的,代码里面有对其的应用。
再说一下,淘宝麻烦的地方的在于它和好搜和百度都不一样,它res.data.result得到的值是一个二维数组,这需要我们把它提取出来,然后转换为一个新的一维数组。