[英]How to use filterBy in Vue.js
I am putting together a simple book sorter app and I am having some trouble using the filterBy
filter. 我正在整理一个简单的书本分类器应用程序,使用filterBy
过滤器时遇到了一些麻烦。 The filter works fine for filtering the non-fiction
genre
but for some reason it does not work for fiction
. 该过滤器可以很好地过滤non-fiction
genre
但是由于某种原因,它不适用于fiction
。 I want to display the book titles and authors, and then in the input field, filter through the list of books being displayed by genre. 我要显示书名和作者,然后在输入字段中筛选按类型显示的书的列表。 So if I write fiction in the input field, it should only display the fiction books. 因此,如果我在输入字段中写小说,它应该只显示小说书。 This is what my view looks like: 这是我的观点:
<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>
And here is my app.js
: 这是我的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,
});
There is no problem with your setup, Vue's filterBy is working fine in your example. 您的设置没有问题,Vue的filterBy在您的示例中运行良好。 When you type fiction
, it will show all Books because they all have the word fiction
in the genre, meaning that: fiction
and non-fiction
both contains fiction
, returning true
. 当您键入fiction
,它会显示所有的书籍,因为它们都具有字fiction
在体裁,即: fiction
和non-fiction
既包含fiction
,返回true
。
Create a custom filter like this: 创建一个自定义过滤器,如下所示:
Vue.filter('match', function (value, input) {
return input ? value.filter(function(item) {
return item.genre === input ? value : null;
}) : value;
});
And change selection from an input to dropdown: 并将选择从输入更改为下拉菜单:
<select v-model="genre">
<option value="" selected>Select Genre</option>
<option value="fiction">Fiction</option>
<option value="non-fiction">Non-Fiction</option>
</select>
Here is a fiddle implementing it: https://jsfiddle.net/crabbly/br8huz7c/ 这是一个实现它的小提琴: https : //jsfiddle.net/crabbly/br8huz7c/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.