You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js中如何在聊天消息中仅显示不重复的日期

Vue.js聊天消息中仅展示不重复日期的实现方法

方法一:通过计算属性按日期分组

先将消息数据按日期分组,同一日期的消息归为一组,渲染时仅在每组顶部显示一次日期:

<template>
  <div class="chat-container">
    <div v-for="(group, date) in groupedMessages" :key="date">
      <div class="date-label">{{ date }}</div>
      <div v-for="msg in group" :key="msg.id" class="chat-message">
        {{ msg.message }}
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: [
        {id: 1,message: 'hi', created_at: '2023-02-16 00:44:41'},
        {id: 2,message: 'how are you?', created_at: '2023-02-16 01:00:00'},
        {id: 3,message: 'hello', created_at: '2023-03-01 12:00:00'},
        {id: 5,message: 'hi', created_at: '2023-03-01 15:56:00'},
      ]
    }
  },
  computed: {
    groupedMessages() {
      return this.message.reduce((groups, msg) => {
        const date = msg.created_at.split(' ')[0];
        if (!groups[date]) groups[date] = [];
        groups[date].push(msg);
        return groups;
      }, {});
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 600px;
  margin: 0 auto;
}
.date-label {
  text-align: center;
  margin: 10px 0;
  color: #999;
  font-size: 14px;
}
.chat-message {
  padding: 8px 12px;
  margin: 5px 0;
  background-color: #f0f0f0;
  border-radius: 4px;
}
</style>

方法二:渲染时直接判断相邻消息的日期

无需修改数据结构,遍历消息时对比当前与前一条消息的日期,仅当日期不同时显示日期标签:

<template>
  <div class="chat-container">
    <div v-for="(msg, index) in message" :key="msg.id" class="chat-item">
      <div v-if="!index || getDate(message[index-1].created_at) !== getDate(msg.created_at)" class="date-label">
        {{ getDate(msg.created_at) }}
      </div>
      <div class="chat-message">{{ msg.message }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: [
        {id: 1,message: 'hi', created_at: '2023-02-16 00:44:41'},
        {id: 2,message: 'how are you?', created_at: '2023-02-16 01:00:00'},
        {id: 3,message: 'hello', created_at: '2023-03-01 12:00:00'},
        {id: 5,message: 'hi', created_at: '2023-03-01 15:56:00'},
      ]
    }
  },
  methods: {
    getDate(datetime) {
      return datetime.split(' ')[0];
    }
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 600px;
  margin: 0 auto;
}
.date-label {
  text-align: center;
  margin: 10px 0;
  color: #999;
  font-size: 14px;
}
.chat-message {
  padding: 8px 12px;
  margin: 5px 0;
  background-color: #f0f0f0;
  border-radius: 4px;
}
</style>

以上两种方案都能实现同一日期消息仅显示一次日期的效果,可根据实际场景选择使用。

内容的提问来源于stack exchange,提问作者kwang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 06:12:51