gpt4 book ai didi

javascript - 在VueJS中使用列表渲染时如何对列表排序

转载 作者:行者123 更新时间:2023-12-03 06:45:24 24 4
gpt4 key购买 nike

我正在Vue2中使用列表渲染。该列表呈现为OK,但根据我数组中数据的顺序进行排序。因此,我需要按标题(a-z)对屏幕上的每个项目进行排序。当我也使用搜索输入(filteredBlogs)时,我似乎无法弄清楚该如何做。任何帮助欢迎。

   const app = new Vue({
el: '#app',
data: {
search: '',
blogs: [
{
title: 'Northern Towns' ,
location: 'Leeds'
},
{
title: 'Things to do in Leeds' ,
location: 'Yorkshire'
},
{
title: 'Visit the beach',
location: 'Cornwall'
}
]
},
computed: {
filteredBlogs:function(){
return this.blogs.filter((blog) => {
return blog.title.toLowerCase().match(this.search.toLowerCase()) || blog.location.toLowerCase().match(this.search.toLowerCase());
.sort((a, b) => {
if (a.title < b.title)
return -1;
if (a.title > b.title)
return 1;
return 0;
});
}
}
});

HTML如下;
<div id="app">
<label>
Search name: <input type="text" v-model='searchString'>
</label> <br>
<li v-for='item in filteredBlogs' :key='item.id' class="my-list-item">
{{item.title}}
</li>
</div>

最佳答案

首先过滤原始数组,然后对过滤后的数组进行排序

computed: {
filteredBlogs:function(){
const filteredBlogs = this.blogs.filter((blog) => blog.title.toLowerCase().match(this.search.toLowerCase()) || blog.location.toLowerCase().match(this.search.toLowerCase()))
filteredBlogs.sort((a, b) => {
if (a.title < b.title)
return -1;
if (a.title > b.title)
return 1;
return 0;
});
return filteredBlogs
}
}

关于javascript - 在VueJS中使用列表渲染时如何对列表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61694335/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com