如何在Vue.js中使用filterBy

时间:2016-05-28 16:31:10

标签: javascript vue.js

我正在整理一个简单的书籍分类器应用程序,我在使用filterBy过滤器时遇到了一些麻烦。过滤器可以正常过滤non-fiction genre但由于某种原因它不适用于fiction。我想显示书名和作者,然后在输入字段中筛选出按流派显示的书籍列表。因此,如果我在输入字段中写小说,它应该只显示小说书。这就是我的观点:

       <div id="app">
            <h1>{{title}}</h1>
              <div id="input">
               <input type="text" v-model="genre" placeholder="Search fiction/non-fiction">
            </div>
             <div id="display-books" v-for=" book in books | filterBy genre in 'genre' ">
               <span>Title: {{book.title}}</span>
               <span>Author: {{book.author}}</span>      
        </div>  
    </div>

这是我的app.js

var appData = { 
  title: 'Book Sorter',
  filters: 'Search filter',
  filtertext: '* only show title if book is available',
  genre: '',
  books:
    [
      {genre: "fiction", title: "The Hobbit", author: "J.R.R Tolkien", available: false},
      {genre: "non-fiction", title: "Homage to Catalonia", author: "George Orwell", available: true},
      {genre: "non-fiction", title: "The Tipping Point", author: "Malcolm Gladwell", available: false},
      {genre: "fiction", title: "Lord of the Flies", author: "William Golding", available: true},
      {genre: "fiction", title: "The Call of the Wild", author: "Jack London", available: true}   
    ]

}
new Vue({
   el: "#app",
   data: appData,

});

1 个答案:

答案 0 :(得分:1)

您的设置没有问题,Vue的filterBy在您的示例中运行正常。当您输入fiction时,它会显示所有图书,因为它们在该类型中都有fiction字样,这意味着:fictionnon-fiction都包含fiction ,返回true

创建一个这样的自定义过滤器:

Vue.filter('match', function (value, input) {
  return input ? value.filter(function(item) {
     return item.genre === input ? value : null;
  }) : value;
});

将选择从输入更改为下拉列表:

<select v-model="genre">
    <option value="" selected>Select Genre</option> 
    <option value="fiction">Fiction</option>
    <option value="non-fiction">Non-Fiction</option>
</select>

以下是实施它的小提琴:https://jsfiddle.net/crabbly/br8huz7c/