2

How do I filter through an array using a computed property in Vue.js 2.0? This task was quite trivial in older versions of Vue, but now it is more involved. I am displaying data in a table:

 <tr v-for="person in filterPeople">
  <td>{{person.name}}</td>
  <td>{{person.age}}</td> 
</tr>

and I have an input field where I can filter through the names and ages. I am not sure what I am doing wrong here:

computed: {

  filterPeople: function(){
    var self = this
    return this.people.filter(function(p){
      return p.name.indexOf(self.searchDetails) > - 1
   })  
  }
}

If I type in the input it does not filter the people by name or age as I expect. Demo: http://codepen.io/p-adams/pen/AXPKko

2
  • Please edit your question to show the relevant code directly in the question body. Commented Aug 2, 2016 at 3:05
  • Edited my question Commented Aug 2, 2016 at 3:11

1 Answer 1

5

Your problem is really simple. You are using an input tag inside of a table. Try adding a containing div tag. Give it the app id and put the input element in it. This should fix the problem.

<div id="app">
  <input
         class="form-control"
         v-model="searchDetails"
         placeholder="filter by name or age"
         >
    <table class="table table-striped" >
      <thead>
      ...rest of code

Vue is still constrained by some of the rules of HTML and one of those is table tags can only have certain tags as direct children.

Sign up to request clarification or add additional context in comments.

6 Comments

Ahh yes. Not sure how I missed that. Thanks.
It's actually somewhat easy to do when you are thinking in terms of Vue. Because normally you have a whole lot more flexibility with templates.
Okay. I wonder why I am unable to filter by age. Seems to only work with the names. Things were much easier with built-in filters.
p.name.indexOf(self.searchDetails) > - 1 is only filtering by p.name. You may need to write two filter functions and use one if the searchDetails is text and another if it is a number.
Perhaps because the number coming in through input is actually a string and my filter is trying to match it to an integer value. Either case, it does seem like I need two filter function.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.