我正在整理一个简单的书分类器应用程序,使用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,

});

最佳答案

您的设置没有问题,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/

关于javascript - 如何在Vue.js中使用filterBy,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37501392/

10-09 19:01