Javascript 在VueJS中使用列表呈现时,如何对列表进行排序
我正在Vue2中使用列表渲染。列表呈现为OK,但根据数组中数据的顺序排序。因此,我需要按标题(a-z)对屏幕上的每个项目进行排序。当我也在使用搜索输入(filteredBlogs)时,我似乎不知道如何做到这一点。欢迎任何帮助Javascript 在VueJS中使用列表呈现时,如何对列表进行排序,javascript,vue.js,vuejs2,Javascript,Vue.js,Vuejs2,我正在Vue2中使用列表渲染。列表呈现为OK,但根据数组中数据的顺序排序。因此,我需要按标题(a-z)对屏幕上的每个项目进行排序。当我也在使用搜索输入(filteredBlogs)时,我似乎不知道如何做到这一点。欢迎任何帮助 const app = new Vue({ el: '#app', data: { search: '', blogs: [ {
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;
});
}
}
});
const-app=新的Vue({
el:“#应用程序”,
数据:{
搜索:“”,
博客:[
{
标题:“北方城镇”,
地点:利兹
},
{
标题:“利兹的事情”,
地点:'约克郡'
},
{
标题:“参观海滩”,
地点:“康沃尔”
}
]
},
计算:{
filteredBlogs:函数(){
返回this.blogs.filter((blog)=>{
返回blog.title.toLowerCase().match(this.search.toLowerCase())| | blog.location.toLowerCase().match(this.search.toLowerCase());
.排序((a,b)=>{
如果(a.标题b.标题)
返回1;
返回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>
搜索名称:
{{item.title}
首先过滤原始数组,然后对过滤后的数组进行排序
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
}
}
计算:{
filteredBlogs:函数(){
const filteredBlogs=this.blogs.filter((blog)=>blog.title.toLowerCase().match(this.search.toLowerCase())| | blog.location.toLowerCase().match(this.search.toLowerCase())
filteredBlogs.sort((a,b)=>{
如果(a.标题b.标题)
返回1;
返回0;
});
返回filteredBlogs
}
}