VueJS v-else statement rendering multiple times

I have a little problem with a VueJs app. I have an array with certain dates and another array with some other items fetched from an API that looks like this.

const datesArr = [25-09-2020, 26-09-2020, 27-09-2020, 28-10-2020];

and the fetched array items which looks like this

const fetchedArr = {
  [
    name: "Product 1",
    description: "Lorem ipsum",
    price: 25,
    date: "25-10-2020"
  ],
  [
    name: "Product 2",
    description: "Lorem ipsum",
    price: 35,
    date: "26-10-2020"
  ],
  [
    name: "Product 3",
    description: "Lorem ipsum",
    price: 15,
    date: "28-10-2020"
  ]
}

What i want to do is to show for every date from dates array, the tasks from fetched api to it’s coresponding date.

This is my vuejs code.

<div
   v-for="(day, index) in nextSixDays"
   :key="index"
   >
<div >{{day.day == nextSixDays[0].day ? 'Tomorrow' : day.formatted}}</div>
<div
   v-for="(task, index) in tasks"
   :key="index"
   >
   <div
      v-if="day.day == task.date"
      >
      {{task.name}}
   </div>
   <div v-else>No tasks for this day</div>
</div>

And this is the result

enter image description here

As you see i have 12 tasks which are from the API and if there are some tasks that matches those days from the first array, they are showed, but it is also showing the else statement for the remaining tasks which do not correspond to that day. I want to show it only one time and just for those days which do not have corresponding tasks.

Thank you in advance!

Answer

create the following method

methods: {
  haveTask(day) {
    return this.tasks.some(task => task.day === day)
  }
}

change the markup as follows:

<template v-if="haveTask(day.day)">
  <div v-for="(task, index) in tasks" :key="index">
    <div v-if="day.day == task.date">
      {{task.name}}
    </div>
  </div>
</template>
<div v-else>No tasks for this day</div>

There’s other, possibly better, ways to achieve this, but this is probably the way with the least amount of changes

You could possibly even do this:

<template v-if="tasks.some(task => task.day === day.day)">

Without needing to add a method at all

Leave a Reply

Your email address will not be published. Required fields are marked *