【发布时间】:2021-02-14 07:35:02
【问题描述】:
我正在学习 vue.js,并且正在尝试使用范围日期的过滤功能。场景是:首先按类型过滤,然后按日期范围过滤(有开始日期和结束日期)。选择结束日期后将显示结果。我创建了第一个过滤器,它是类型,它可以工作。我已经搜索了日期范围的各种方法,但仍然找不到合适的方法。如何使用computed 或methods 过滤日期范围?如果有人知道,请您一步一步告诉我吗?
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>
【问题讨论】:
-
您是如何尝试实现数据过滤器的?
标签: javascript vue.js vuejs2