使用 Vue.js 仿百度搜索框的实例代码
程序员文章站
2022-04-09 15:25:42
整理文档,搜刮出一个使用 vue.js 仿百度搜索框的实例代码,稍微整理精简一下做下分享。
整理文档,搜刮出一个使用 vue.js 仿百度搜索框的实例代码,稍微整理精简一下做下分享。
<!doctype html> <html> <head> <meta charset="utf-8"> <title>vue demo</title> <style type="text/css"> .bg { background: #ccc; } </style> <script src="https://cdn.bootcss.com/vue/2.1.7/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: function(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; }) }, down: function() { this.nowindex++; if (this.nowindex == this.result.length) { this.nowindex = -1; this.inputtext = this.text; } }, up: function() { 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> <div id="box"> <input type="text" placeholder="请输入搜索内容" v-model='inputtext' @keyup='show($event)' @keydown.down='down()' @keydown.up.prevent='up()'> <ul> <li v-for="(item, index) in result" :class='{bg: index==nowindex}'> {{item}} </li> </ul> </div> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。