I'm learning about vue.js, and I'm trying out a filter feature using range date. The scenario is: first filter by type, then filter by date range (there are start and end dates). The results will appear when the end date is selected. I have created the first filter, which is type, and it works. I have searched various ways for the date range, but still can't find the right one. How do I filter date ranges using computed or methods? If anyone knows, can you please tell me step by step?
new Vue({
el: '#app',
data: {
selectedType: '',
startDate:null,
endDate:null,
items: [
{
name: 'Nolan',
type: 'mercedes',
year: '2020',
country: 'england',
date: '08/01/2020'
},
{
name: 'Edgar',
type: 'bmw',
year: '2020',
country:'belgium',
date: '08/11/2020'
},
{
name: 'John',
type: 'bmw',
year: '2019',
country: 'england',
date: '08/21/2020'
},
{
name: 'Axel',
type: 'mercedes',
year: '2020',
country: 'england',
date: '08/01/2020'
}
]
},
computed: {
filterItem: function () {
let filterType = this.selectedType
if (!filterType) return this.items; // when filterType not selected
let startDate = this.startDate && new Date(this.startDate);
let endDate = this.endDate && new Date(this.endDate);
return this.items.filter(item => {
return item.type == filterType;
}).filter(item => {
const itemDate = new Date(item.date)
if (startDate && endDate) {
return startDate <= itemDate && itemDate <= endDate;
}
if (startDate && !endDate) {
return startDate <= itemDate;
}
if (!startDate && endDate) {
return itemDate <= endDate;
}
return true; // when neither startDate nor endDate selected
})
}
}
})
.list-item {
margin-top: 50px;
}
#app {
position: relative;
padding-bottom: 200px;
}
span {
margin: 0 15px;
cursor: pointer;
}
.filter-box {
margin-top: 15px;
}
.card {
box-shadow: 0px 10px 16px rgba(0, 0, 0, 0.16);
width: 400px;
padding: 20px 30px;
margin-bottom: 30px;
}
button {
background-color: #1cf478;
border: none;
padding: 10px 25px;
font-weight: bold;
border-radius: 15px;
}
select,input {
border: none;
padding: 10px 15px;
background-color: #c1c1c1;
border-radius: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="app">
<label for="">Type</label>
<select v-model="selectedType">
<option value="" disabled selected hidden>Type</option>
<option value="mercedes">Mercedes</option>
<option value="bmw">BMW</option>
</select>
<label for="">From</label>
<input type="date" v-model="startDate">
<label for="">To</label>
<input type="date" v-model="endDate">
<div class="list-item" v-for="item in filterItem">
<div class="card">
<p>Name: {{ item.name }}</p>
<p>Car: {{ item.type }}</p>
<p>Date: {{ item.date }}</p>
<p>Country: {{ item.country }}</p>
</div>
</div>
</div>