【发布时间】:2020-11-28 03:05:55
【问题描述】:
我正在尝试对 Vue 中的对象数组进行过滤和排序。目前我正在过滤数组,但我想添加一个排序功能。我创建了一个下拉组件并使用事件总线将单击的下拉项的结果发送到我想要进行排序的组件。
但是,我不确定如何同时显示过滤器和排序选项。
渲染对象数组并对其进行过滤/排序的组件
<template>
<div class="cards">
<CountdownCard
v-for="(event, index) in filteredItems"
:key="index"
:event="event"
/>
</div>
</template>
<script>
import CountdownCard from '@/components/CountdownCard'
import EventBus from '@/components/EventBus'
export default {
components: {
CountdownCard
},
data() {
return {
events: [
{
title: 'Christmas',
date: 'December 25, 2020',
emoji: '????????',
type: 'holiday',
year: 2020,
month: 11,
day: 21,
hour: 0,
minute: 0
},
{
title: 'Spring',
date: 'March 21, 2020',
emoji: '????',
type: 'season',
year: 2021,
month: 2,
day: 21,
hour: 0,
minute: 0
},
{
title: "Tyler's Birthday",
date: 'September 14, 2020',
emoji: '????',
type: 'custom',
year: 2020,
month: 8,
day: 14,
hour: 0,
minute: 0
}
filter: '',
sort: ''
}
},
mounted() {
return (
EventBus.$on('filter-catagories', filter => {
this.filter = filter
}),
EventBus.$on('sort-catagories', sort => {
this.sort = sort
})
)
},
computed: {
filteredItems: function() {
// filters at work
return (
this.events
// search filter
.filter(event => {
return event.title
.toLowerCase()
.includes(this.updateSearch.toLowerCase())
})
// category filters
.filter(event => {
if (this.filter == '' || this.filter == 'all') {
return this.events
} else {
return event.type == this.filter
}
})
)
},
sortedItems: function:{
// logic for sorting
}
}
</script>
这是我的下拉组件
<template>
<div class="dropDownContainer">
<div class="selection" :class="{ opened: opened }" @click="toggle">
<span class="selectionText">
{{ selected.label }}
<span class="downArrow"></span>
</span>
</div>
<transition name="grow">
<div class="options" v-if="opened">
<span
v-for="(option, index) in choices"
:key="index"
@click="makeSelection(option), emitSort(option.name)"
>
{{ option.label }}
</span>
</div>
</transition>
</div>
</template>
<script>
import EventBus from '@/components/EventBus'
export default {
props: {
choices: Array,
menuLabel: String
},
data: function() {
return {
selected: this.choices[0],
opened: false,
sortResult: ''
}
},
methods: {
toggle: function() {
this.opened = !this.opened
},
makeSelection: function(selected) {
this.selected = selected
this.opened = false
},
emitSort(option) {
this.sortResult = option
EventBus.$emit('sort-catagories', this.sortResult)
}
}
}
</script>
【问题讨论】:
-
你不能只对
filteredItems的计算中的项目进行排序吗?
标签: javascript arrays sorting vue.js vue-component