CIB
CIB

Reputation: 785

Filter array results on keyup

I have an array of names that I loop over using v-for I'm trying to filter these results when a user starts typing in a search box.

I've added my code below for reference if I do my loop as v-for="entry in entries" then it output the array but doesn't work with the computed and filteredList function

<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())
            })   
        }
    }
}

Upvotes: 1

Views: 1899

Answers (1)

Allkin
Allkin

Reputation: 1098

Try to move the search prop in to data option like this:

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())
            })   
        }
    }
}

Also add a check if the search prop is empty to return the full entries list.

Demo fiddle

Upvotes: 1

Related Questions