这次给大家带来vue.js 2.0实现百度搜索框,vue.js 2.0实现百度搜索框的注意事项有哪些,下面就是实战案例,一起来看一下。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=2.0, maximum-scale=1.0, minimum-scale=1.0">
<title>vue模拟百度搜索</title>
<style type="text/css">
body, html{
padding: 0;
margin: 0;
}
#box{
margin-top: 80px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.input{
width: 500px;
height: 30px;
text-indent: 4px;
}
.baidu input{
height: 30px;
cursor: pointer;
color: #fff;
letter-spacing: 1px;
background: #3385ff;
border: 1px solid #2d78f4;
}
ul{
padding: 0;
margin-top: 6px;
}
li{
list-style: none;
margin: 4px;
}
li:hover{
background: #ccc;
}
.bgcolor {
background: #ccc;
}
</style>
<script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
<script src="https://cdn.bootcss.com/vue-resource/1.3.1/vue-resource.min.js"></script>
<script type="text/javascript">
window.onload = function() {
new vue({
el: '#box',
data: {
inputtext: '',
text: '',
nowindex: -1,
result: []
},
methods: {
show (ev) {
if (ev.keycode == 38 || ev.keycode == 40) {
if (this.nowindex < -1){
return;
}
if (this.nowindex != this.result.length && this.nowindex != -1) {
this.inputtext = this.result[this.nowindex];
}
return;
}
if (ev.keycode == 13) {
window.open('https://www.baidu.com/s?wd=' + this.inputtext, '_blank');
this.inputtext = '';
}
this.text = this.inputtext;
this.$http.jsonp('https://sp0.baidu.com/5a1fazu8aa54nxgko9wtanf6hhy/su', {
params: {
wd: this.inputtext
},
jsonp: 'cb'
}).then(res => {
this.result = res.data.s;
})
},
goto () {
window.open('https://www.baidu.com/s?wd=' + this.inputtext, '_blank');
this.inputtext = '';
},
gotoitem(item) {
window.open('https://www.baidu.com/s?wd=' + item, '_blank');
this.inputtext = '';
},
down () {
this.nowindex++;
if (this.nowindex == this.result.length) {
this.nowindex = -1;
this.inputtext = this.text;
}
},
up () {
this.nowindex--;
if (this.nowindex < -1){
this.nowindex = -1;
return;
}
if (this.nowindex == -1) {
this.nowindex = this.result.length;
this.inputtext = this.text;
}
}
}
});
}
</script>
</head>
<body>
<p id="box">
<img src="https://ss0.bdstatic.com/5av1bjqh_q23odcf/static/superman/img/logo/bd_logo1_31bdc765.png" width="270" height="129">
<p>
<p>
<input
type="text"
class="input"
placeholder="请输入搜索内容 "
v-model='inputtext'
@keyup='show($event)'
@keydown.down='down()'
@keydown.up.prevent='up()'
>
<span class="baidu" @click="goto()">
<input type="submit" value="百度一下" >
</span>
</p>
<ul>
<li v-for="(item, index) in result" :class='{bgcolor: index==nowindex}' @click="gotoitem(item)">
{{item}}
</li>
</ul>
</p>
</p>
</body>
</html>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
以上就是vue.js 2.0实现百度搜索框的详细内容。