Vue搜索

作者: awesome_lewis | 来源:发表于2017-07-11 15:10 被阅读59次

2017.10.11更新:
先前的代码中,当按下方向键上键或下键时,相应条目高亮显示,此时如果按下左右方向键,仍然会触发get方法,应对此予以控制;
当文本框文字改变时,会触发get方法,搜索结果被更新,但之前高亮的条目会一直保持高亮;
以上缺陷均已修复。


这篇文章的代码源自智能社出品的Vue教程,由于视频录制于2016年,部分代码在vue2.0下会报错,这里已做了相应的调整;此外,还修正了一些语义不清晰的变量

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>vue搜索</title>
    <style>
        .gray{
            background-color: #ccc;
        }
    </style>
    <script src="http://cdn.bootcss.com/vue/2.3.3/vue.min.js"></script>
    <script src="http://cdn.bootcss.com/vue-resource/1.3.4/vue-resource.js"></script>
</head>

<body>
    <div id="box">
        <input
            type="text"
            v-model="userInput"
            @keyup="get($event)"
            @keydown.down="changeDown()"
            @keydown.up.prevent="changeUp()"
        >
        <ul>
            <li v-for="(value,index) in searchResult" :class="{gray:index==now}">{{value}}</li>
        </ul>
        <p v-show="searchResult.length==0">暂无数据...</p>
    </div>
    
    <script>
    new Vue({
        el: '#box',
        data: {
            searchResult: [],
            userInput: '',
            now: -1
        },
        methods: {
            get(ev) {
                if (/^(3[7-9]|40)$/.test(ev.keyCode)) return;

                if (ev.keyCode == 13) {
                    window.open('https://www.baidu.com/s?wd=' + this.userInput);
                    this.userInput = '';
                }

                this.$http.jsonp('https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su', {
                    params:{
                        wd: this.userInput
                    },
                    jsonp: 'cb'
                }).then(function(res) {
                    this.now = -1;
                    this.searchResult = res.data.s;
                }, function(res) {
                    alert(res.status);
                });
            },
            changeDown() {
                this.now++;
                if (this.now == this.searchResult.length) this.now = -1;
                this.userInput = this.searchResult[this.now];
            },
            changeUp() {
                this.now--;
                if (this.now == -2) this.now = this.searchResult.length - 1;
                this.userInput = this.searchResult[this.now];
            }
        }
    });
    </script>
</body>
</html>

相关文章

网友评论

    本文标题:Vue搜索

    本文链接:https://www.haomeiwen.com/subject/unpyhxtx.html