I'm building a date range selector, and while this works, I feel like I'm making it more complicated than it needs to be. Is there a more elegant way of writing this?
Possibly using computed values or watches?
<template>
<form>
<select @change="rangeSelection">
<option
v-for="(option, key) in rangeOptions"
:key="key"
:value="key">
{{option.display}}
</option>
</select>
</form>
</template>
<script>
import moment from 'moment';
export default {
name: 'DateRangeChooser',
data: () => {
return {
selectedRange: "last7Days",
startDate: moment().subtract(8, 'days'),
endDate: moment().subtract(1, 'days'),
rangeOptions: {
last7Days: {
display: 'Last 7 Days',
startDate: moment().subtract(8, 'days'),
endDate: moment().subtract(1, 'days')
},
lastWeek: {
display: 'Last Week',
startDate: moment().startOf('week').subtract(1, 'week'),
endDate: moment().endOf('week').subtract(1, 'week')
},
last30days: {
display: 'Last 30 days',
startDate: moment().subtract(31, 'days'),
endDate: moment().subtract(1, 'days')
}
}
}
},
methods: {
rangeSelection: function(e){
this.endDate = this.rangeOptions[e.currentTarget.value].endDate;
this.startDate = this.rangeOptions[e.currentTarget.value].startDate;
}
}
};
</script>
date-fns
instead ofmoment
, since moment requires you to embed the entire library, and date-fns lets you import only the parts you need \$\endgroup\$