【问题标题】:VueJS update variable in loopVueJS在循环中更新变量
【发布时间】:2021-02-22 07:05:05
【问题描述】:

我正在尝试获取对话组件的“最后一个新日期”,但是当我更新我的 temp_date 以与 message.date 进行比较时,我有一个“无限更新循环”。

我找到了这个话题You may have an infinite update loop in a component render function 但我不知道如何将它应用到我的案例中......

我做了一个小提琴,它是正确的方法吗?有什么最好的做法吗?

https://jsfiddle.net/odgj7wu5/1/

【问题讨论】:

    标签: vuejs2


    【解决方案1】:

    如果你像这样修改你的模板

    <div v-for="message in uniqueMessages" :key="message.id">
    

    并像这样定义计算属性uniqueMessages

    computed:
    {
       uniqueMessages()
       {
         return this.messages.filter((value, index, self) => self.indexOf(value) === index)
       }
    }
    

    您将不需要 showDate 函数。

    【讨论】:

    • 但我不会收到所有消息,对吧?我想获取除唯一日期之外的所有消息。
    • 您将只获得每个日期的第一条消息(出现在数组中较早的消息) - 您可能需要对数组进行排序,以便给定日期的最新消息在较旧的消息之前出现。
    【解决方案2】:

    好吧,我使用了其他格式的数组,如下所示:

    mounted() {
        let dates: string[];
        dates = this.messages.map( message => message.date);
        const uniq_dates = [...new Set(dates)];
        for (const date of uniq_dates) {
            this.ordered_messages.push({
                date: date,
                messages: this.messages.filter(message => date == message.date)
            });
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-17
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多