首页 > 解决方案 > Vue js - 根据当前时间显示列表中的元素

问题描述

我从 API 接收对象(行程)列表,我想检查是否有任何行程对象满足以下逻辑:

行程对象包括 -> startTime、estimatedTime、begin、destination

逻辑:如果有满足的行程startTime + estimatedTime < currentTime,则显示该组件。

目前正在显示列表中的所有行程:

    <div class="col-xs-24">
        <Loading :data="passengerTrips" :hideOnEmpty="true">
            <h2 slot="title" > Trips which im going</h2>
            <div class="trips-list">
                <Trip v-for="trip in passengerTrips" :trip="trip" :user="user"></Trip>
            </div>
        </Loading>
    </div>

<script>
    watch: {
    passengerTrips: function () {
        this.updateScroll();
    },
    computed: {
    ...mapGetters({
        passengerTrips: 'myTrips/passengerTrips'
    }),
</script>

我是 vue 的新手,所以任何建议都将不胜感激。

标签: vue.jsconditional-statementsvue-component

解决方案


startTime,estimatedTime,开始,目的地

您可以在商店中使用吸气剂:

getters: {
  ...,
  tripsOnTime: state => {
    const currentTime = new Date(); // Format the time based on your requirements
    // return only the trips that meet the condition
    // Validation to check if trip is not undefined/null
    return state.trips.filter(trip => trip && trip.startTime + trip.estimatedTime < currentTime
  },
  ...
}

现在您可以添加它:

<script>
  watch: {
    passengerTrips: function () {
      this.updateScroll();
    },
  computed: {
    ...mapGetters({
    passengerTrips: 'myTrips/passengerTrips',
    tripsOnTime: 'myTrips/tripsOnTime',    
  }),
</script>

我添加trip到验证:

return state.trips.filter(trip => trip && trip.startTime + trip.estimatedTime < currentTime

如果你想检查每个属性,那么你可以用&&操作符来做,对象的 hasOwnProperty 方法。


推荐阅读