使用 Vue.js 仿百度搜索框的实例代码

发布时间:2020-09-09 11:57:30 作者:与蟒唯舞
来源:脚本之家 阅读:139

整理文档,搜刮出一个使用 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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 在vue 中使用Stylus
  2. bootstrap和vue能够同时使用吗

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue.js 搜索 ue

上一篇:Oracle中Drop,Delete,Truancate表恢复

下一篇:this.$toast() 了解一下?

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》