我有一个Vue.js变量列表,我想在按项目值过滤后获取列表的最后一个值:
var users = new Vue({
el: '#get-users',
data: {
items: [
{ id: 1, username: 'che', firstName: 'cheikh', group: 2 },
{ id: 1, username: 'lam', firstName: 'lamine', group: 1 },
{ id: 1, username: 'abd', firstName: 'abdoulaye', group: 1 },
{ id: 1, username: 'dem', firstName: 'demba', group: 3 },
{ id: 1, username: 'fat', firstName: 'fatou', group: 2 },
{ id: 1, username: 'pen', firstName: 'penda', group: 2 },
{ id: 1, username: 'olym', firstName: 'oly', group: 1 },
{ id: 1, username: 'aic', firstName: 'aicha', group: 1 },
]
}
})
项目列表是按add_day排序的(此处未显示)。所以我想用group
过滤项目并获取最后一个值。在这里,如果我按组:1进行过滤,我应该有
{ id: 1, username: 'aic', firstName: 'aicha', group: 1 }
答案 0 :(得分:1)
这里,我使用vue computed
来过滤第1组项目并获取第1组项目的最后一个元素。
data: {
items: [
{ id: 1, username: 'che', firstName: 'cheikh', group: 2 },
{ id: 1, username: 'lam', firstName: 'lamine', group: 1 },
{ id: 1, username: 'abd', firstName: 'abdoulaye', group: 1 },
{ id: 1, username: 'dem', firstName: 'demba', group: 3 },
{ id: 1, username: 'fat', firstName: 'fatou', group: 2 },
{ id: 1, username: 'pen', firstName: 'penda', group: 2 },
{ id: 1, username: 'olym', firstName: 'oly', group: 1 },
{ id: 1, username: 'aic', firstName: 'aicha', group: 1 },
]
},
computed: {
// a computed getter
filteredLastItem: function() {
// filtering based upon group 1 items...
let getLastItem = this.items.filter(item => { return item.group == 1 })
// fetching the last item...
return getLastItem[getLastItem.length -1]
}
}
要签入html标签
<p>
{{filteredLastItem}}
</p>
答案 1 :(得分:0)
不确定我是否完全理解这个问题,但这可能有用:
function getFilteredLast(group) {
let filteredItems = data.items.filter(item => item.group === group)
return filteredItems.length > 0
? filteredItems[filteredItems.length - 1];
: null;
}
答案 2 :(得分:0)
首先,您可以定义一个计算属性,以使用group === 1
computed: {
group1 () {
return this.items.filter(item => {
item.group === 1
})
}
}
然后,您可以在需要时获取此计算属性的最后一个值:
this.group1[this.group1.length - 1]
答案 3 :(得分:0)
这应该有效
var users = new Vue({
el: '#get-users',
data: {
items: [
{ id: 1, username: 'che', firstName: 'cheikh', group: 2 },
{ id: 1, username: 'lam', firstName: 'lamine', group: 1 },
{ id: 1, username: 'abd', firstName: 'abdoulaye', group: 1 },
{ id: 1, username: 'dem', firstName: 'demba', group: 3 },
{ id: 1, username: 'fat', firstName: 'fatou', group: 2 },
{ id: 1, username: 'pen', firstName: 'penda', group: 2 },
{ id: 1, username: 'olym', firstName: 'oly', group: 1 },
{ id: 1, username: 'aic', firstName: 'aicha', group: 1 }
]
},
methods: {
filteredUsersByGroup: function(group_value){
var filtered = this.items.filter(function(user){
return user.group == group_value;
});
return filtered[filtered.length-1]
},
filteredUsersByUsername: function(username_value){
var filtered = this.items.filter(function(user){
return user.group.toLowerCase().indexOf(username_value.toLowerCase())>=0;
});
return filtered[filtered.length-1]
}
}
})
您也可以使用computed:{}