在keyup上过滤数组结果

时间:2018-08-22 06:47:14

标签: vue.js vuejs2 vue-component v-for

我有一个名称数组,可以使用v-for遍历,当用户开始在搜索框中输入内容时,我试图过滤这些结果。

如果我以v-for="entry in entries"的身份进行循环,则在下面添加了我的代码以供参考,然后它输出了数组,但不适用于计算和过滤列表函数

<template>
    <div class="container-flex">
        <div class="entries">

            <div class="entries__header">
                <div class="entries__header__title">
                    <p>Entries</p>
                </div>

                <div class="entries__header__search">
                    <input 
                        type="text" 
                        name="Search" 
                        class="input input--search" 
                        placeholder="Search..." 
                        v-model="search">
                </div>
            </div>

            <div class="entries__content">
                <ul class="entries__content__list">
                    <li v-for="entry in filteredList">
                        {{ entry.name }}
                    </li>
                </ul>
            </div>

        </div>
    </div>
</template>

<script>

import addEntry from '@/components/add-entry.vue'

export default {
    name: 'entry-list',
    search: '',
    components: {
        addEntry
    },
    data: function() {

        return {
            entries: [
            {
                name: 'Paul'
            }, 
            {
                name: 'Barry'
            },
            {
                name: 'Craig'
            },
            {
                name: 'Zoe'
            }
            ]
        }
    },
    computed: {
        filteredList() {
            return this.entries.filter(entry => {
                return entry.name.toLowerCase().includes(this.search.toLowerCase())
            })   
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将搜索道具移入数据选项,如下所示:

export default {
    name: 'entry-list',
    components: {
        addEntry
    },
    data: function() {

        return {
            search: '',
            entries: [
            {
                name: 'Paul'
            }, 
            {
                name: 'Barry'
            },
            {
                name: 'Craig'
            },
            {
                name: 'Zoe'
            }
            ]
        }
    },
    computed: {
        filteredList() {
            if(this.search === '') return this.entries
            return this.entries.filter(entry => {
                return entry.name.toLowerCase().includes(this.search.toLowerCase())
            })   
        }
    }
}

还添加一个搜索道具是否为空的检查,以返回完整的条目列表。

Demo fiddle