r_batra
r_batra

Reputation: 410

Vuejs Custom Search Filter Not Working With Computed

I am trying to have custom filter search functionality . When i try to filter the records based on keywords in filter search, it does nothing but displays all posts. This always has this.search as ''. What is the potential fix in this case?

<form>
    <fieldset class="w-100 left">
        <input type="text" placeholder="Filter posts by keyword" v-model="search"/>
    </fieldset> 
</form>
<div>
    <div id="mainSec">
        <div v-for="post in filteredPosts">

            <div v-for="result in results" v-if="post.userId == result.id" class="left ml-3 mt-3" > 
                <p >{{result.name}}</p>
                <p>{{result.email}} | {{result.address.city}}</p>
            </div>  
            <p style="float:left;width:100%"><strong>{{post.title.toUpperCase()}}</strong></p>
            <p style="float:left;width:100%">{{post.body}}</p>
        </div>  
    </div>
</div>
</html>
<script>

var  vm = new Vue({
    el: '#mainSec',
    data() {
        return {
            search : '',
            results : [],
            posts : []
        };
    },
    async created() {
            try{
                axios.get(urlUsers).then(response => {
                    this.results = response.data
                });
                axios.get(urlPosts).then(response => {
                    this.posts = response.data
                });

            }
            catch(error){
                console.log("Error is " + error);
            }

    },
    computed : {
        filteredPosts (){
            if(this.search){
                return this.posts.filter((item)=>{
                    return item.title.match(this.search);
            })
        }else{
            return this.posts;
        }
    }
})
</script>

Upvotes: 0

Views: 465

Answers (1)

Daniel
Daniel

Reputation: 35684

It is likely because you're use el: '#mainSec', to target a portion of your html code. That means that the v-model="search" does nothing, and thus the variable never gets updated and the computed never fires.

The easiest way to fix this is to wrap your <form> AND your <div id="mainSec"> with a div that you give the mainSec id to. (or give it a separate id and then reference that in your Vue el attribute.

Upvotes: 1

Related Questions