I am trying to filter and sort an array of objects in Vue. I am able to successfully filter any ranger of filter methods on my list of objects, but when I add a sort function, and conditionally render a specific sort function, the this.sort is undefined in the console. I want to add if statements inside the sort method to dynamically render specfic sorting (ex// alphabetically and time left ...)
<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 {
props: {
milliseconds: {
default: 0
},
seconds: {
default: 0
}
},
components: {
CountdownCard
},
data() {
return {
events: [
{
title: 'Autum',
date: 'September 22, 2020',
emoji: '',
type: 'season',
year: 2020,
month: 8,
day: 22,
hour: 0,
minute: 0
},
{
title: 'Christmas',
date: 'December 25, 2020',
emoji: '',
type: 'holiday',
year: 2020,
month: 11,
day: 21,
hour: 0,
minute: 0
},
],
updateSearch: '',
filter: 'all',
sort: 'alpha'
}
},
mounted() {
return (
EventBus.$on('search-countdowns', search => {
this.updateSearch = search
}),
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
}
})
// sort alpha
.sort(function(a, b) {
if (this.sort == 'alpha') {
if (a.title < b.title) {
return -1
}
if (a.title > b.title) {
return 1
}
return 0
}
// sort dates
if (this.sort == 'timeLeast') {
if (a.year < b.year) {
return 1
}
if (a.year > b.year) {
return -1
}
return 0
}
})
)
}
}
}
</script>
WHy is the this.sort
undefined when right above in the code, this.filter
has no errors?