0

Here's my code:

<div v-for="(message) in messages">
      <div class="message-divider sticky-top pb-2" data-label="Test">&nbsp;</div>
       ...

What I need to achieve is, if current iteration's message.createdAt.seconds differs by day from the previous one to show message-divider element.

So the time format is in seconds like this: 1621515321

How can I achieve this?

Terminus
  • 71
  • 6

2 Answers2

2

You can do variable assignment as part of the template, so you could assign the previous value and compare, but this is not a very good idea. Instead you can use a computed to prepare your array to only have the objects you want, with the data you need. So in this case, you could use a computed to create a new array with objects that have additional flags like className or showDivider etc.

example:

computed:{
  messagesClean(){
    let lastCreatedAt;
    return this.messages.map(message => {
      const ret = {
        ...message,
        showDivider: lastCreatedAt + 3600*24 < message.createdAt.seconds // your custom logic here
      }
      lastCreatedAt = message.createdAt.seconds 
      return ret
    }
  }
}

the logic to determine when the divider gets shown is up to you there, I suspect it may be a bit more complicated than differing by a day.

tony19
  • 125,647
  • 18
  • 229
  • 307
Daniel
  • 34,125
  • 17
  • 102
  • 150
  • 1
    Agree with the solution, not with the logic. Should be `showDivider: lastCreatedAt + 3600*24 < message.createdAt.seconds` (assuming messages are ordered of course) – Michal Levý May 27 '21 at 18:06
  • 1
    agreed (will fix the `>`). But this was just an example, IMHO, the definition _differs by day from the previous one_ is incomplete or unclear. It sounds like the request is that the offset is at least a day, but I think the author likely means that the date is different. For example 23:20 and 00:12 are not off by a day but should probably have a separator. The solution will likely need to compare the dates which is a topic that seemed to be somewhat tangential and has some answers available here https://stackoverflow.com/questions/4428327/checking-if-two-dates-have-the-same-date-info – Daniel May 27 '21 at 18:41
0

You need something like this:

    <div v-if="compEqRef">
      OK
    </div>
    <div v-else >!!OK!!</div>

Here compEqRef could be in computed:

    computed: {
      compEqRef() {
        //do something
      }
    },
newb
  • 16
  • 3
  • @Terminus is looking for a way to compare the value of the variable passed into the loop template function with the value from the previous iteration. I don't think this addresses that. – Daniel May 27 '21 at 15:52