javascript - 列表排序方法不更新顺序
问题描述
我试图深入了解为什么这种排序功能不起作用。
从理论上讲,它应该与此相同:https ://codepen.io/levit/pen/abmXgBR
我有一个从 API 获取的列表:
<BookCard v-for='book in filteredBooks' :key='book.id' :book='book' />
我有一个用于搜索的过滤器,但我的排序不是。这是我的计算属性/方法的数据:
data() {
return {
books: [],
order: 1, // Ascending
search: '',
};
},
computed: {
filteredBooks() {
return this.filterBySearch((this.sortByRating(this.books)));
},
},
methods: {
filterBySearch(books) {
return books.filter((book) => book.volumeInfo.title
.toLowerCase().match(this.search.toLowerCase()));
},
sortByRating(books) {
return books
.sort((r1, r2) => (r2.volumeInfo.averageRating - r1.volumeInfo.averageRating)
* this.order);
},
sort() {
this.order *= -1;
},
},
最后,我有一个按钮来切换顺序:
<button v-bind:class="order === 1 ? 'descending' : 'ascending'" @click="sort">
Reader Rating
</button>
由于我是 Vue 的新手,因此对我可能出错的任何见解都会非常有帮助。
谢谢你。
解决方案
尽量不要将 data 属性作为参数传递,因为它在方法中可用,并且只对过滤后的书籍而不是原始属性进行排序,因为排序会影响它:
computed: {
filteredBooks() {
let filtered= this.filterBySearch().slice();
return this.sortByRating(filtered)
},
},
methods: {
filterBySearch() {
return this.books.filter((book) => book.volumeInfo.title
.toLowerCase().match(this.search.toLowerCase()));
},
sortByRating(books) {
return books.sort((r1, r2) => {
if (
typeof r2.volumeInfo.averageRating === "number" &&
typeof r1.volumeInfo.averageRating === "number"
) {
return (
(r2.volumeInfo.averageRating - r1.volumeInfo.averageRating) *
this.order
);
} else {
return this.order * -1;
}
});
},
sort() {
this.order *= -1;
},
},
推荐阅读
- excel - VBA Word - 快速提取 Excel 文件
- python - How to stop g-mail marking my e-mails as dangerous?
- javascript - javascript:为什么我需要单击两次才能更改显示属性?
- php - PDO prepare with unknown OR statements
- javascript - 如何创建与 express 或 http 反应的服务器?
- android-source - Stop SE Linux from Enforcing on Android AOSP
- java - How to take the values from the variable and enter in the text box?
- java - how to index each feature elasticsearch featurecollection
- python - 通过对具有数字和字符串变量的数据框进行分组来转置
- excel - VBA Excel String concatenation upper than max length, How to?