ronon
191
2
Vue

Search/filter through array from another component

Posted 1 year ago by ronon

I have three vue components. Sidebar, Conversation and Search. I let vue sort the conversations by a timestamp each conversation has, from new to old. Now I need to search them. For this I created a component Search. I already found this piece of code

var _this = this;

                return this.conversations.filter(function (con) {
                    return con.name.toLowerCase().indexOf(_this.searchValue.toLowerCase()) >= 0;
                }); 

I think this will provide a good search experience, but I really don't have a clue where and how to integrate this?

Here are the other components.

Sidebar

<template lang="html"> 
    <div class="col s12 m12 l4 card-panel no-padding" style="margin: 0;" v-show="showSidebar">

            <search :conversations="conversations"></search>

            <conversation :conversations="conversations"></conversation>

    </div>
</template>

<script>
    export default{
        props: ['conversations'],
       
    }
</script>

Conversation

<template lang="html">
    <ul class="collection conversation-collection ">
        <li v-for="(conversation, index) in sortedConversations "
            class="collection-item avatar chat-avatar"
            :class="{'chat-active' : activeIndex === index }"
            @click="changeconversation(conversation.conversation_id, index)">


            <img :src="conversation.image" alt="" class="circle chat-img">
            <span class="title">{{ conversation.name }}</span>
           // Other information 
           
        </li>
    </ul>
</template>

<script>
    export default{
        props: ['conversations','activeIndex'],
        data(){
            return {
                searchValue: ''
            }
        },
        computed: {

            // Sort by last updated timestamp
            sortedConversations: function () {
                let _this = this;

                function compare(a, b) {
                    if(a.updated_at > b.updated_at){
                        return -1;
                    } else {
                        return 1;
                    }
                }
                return this.conversations.sort(compare);
            },


        }

    }
</script>

Search

<template lang="html">
    <div class="chat-search">
        <i class="material-icons icon input-group__append-icon">search</i>
        <input placeholder="Search" id="search-chat" type="text" class="validate" v-model="searchValue" >
    </div>
</template>


<script>

    export default{
        props: ['conversations'],
        data(){
            return {
                searchValue: ''
            }
        }
    }
</script>

Please sign in or create an account to participate in this conversation.