我使用Vue.js构建了群聊消息。我目前正在获取返回如下数组的消息:
"data":[
{
"id":1,
"message":"<p>yo<\/p>",
"removed":"false",
"user":{
"uid":2,
"metadata":{
"username":"Testing"
}
},
"post_date":"2018-02-24 14:30"
},
{
"id":2,
"message":"<p>test<\/p>",
"removed":"false",
"user":{
"uid":1,
"metadata":{
"username":"Admin"
}
},
"post_date":"2018-02-24 22:31"
},
{
"id":3,
"message":"<p>Wassup?<\/p>",
"removed":"false",
"user":{
"uid":1,
"metadata":{
"username":"Admin"
}
},
"post_date":"2018-02-24 22:40"
},
{
"id":12,
"message":"again for testing post date",
"removed":"false",
"user":{
"uid":1,
"metadata":{
"username":"Admin"
}
},
"post_date":"2018-03-04 00:59"
},
{
"id":13,
"message":"Hello!",
"removed":"false",
"user":{
"uid":2,
"metadata":{
"username":"Testing"
}
},
"post_date":"2018-03-04 11:13"
},
{
"id":13,
"message":"<p>Hi!</p>",
"removed":"false",
"user":{
"uid":2,
"metadata":{
"username":"Testing"
}
},
"post_date":"2018-03-04 11:13"
},
],
目前,我只是遍历数据并将每个消息输出到单独的div
。我更希望在同一用户连续发布多个消息时对消息进行分组。
我将如何处理?应该是选项服务器端(也许是可选group
参数?)还是客户端完成?
The problem if I group them by the UID/Username, is that the messages need to be output in order. So if User 1 send three messages, then User 2 send two, then User 1 sends another message, all of user 1s message will be grouped together. Rather the User 1s three messages should be grouped, then User 2s, then it should show User 1s last message.
I solved this problem for myself pretty recently. Here's a full example.
The core business logic for grouping messages, in the above example, can be found under src/store.js
in the addMessage
function.
除非您的服务器还存储了所有消息,并且您没有某种机制可以确保所有客户端之间的因果顺序,否则我建议您在每个客户端上运行逻辑。这样,您可以确保客户在任何情况下都不会看到邮件跳来跳去。最坏的情况是,邮件将显示为未分组。
确定此消息的算法在收到新消息时运行,因此它在每个客户端上运行,但是您也可以对其进行调整以使其适合您的用例!如下所示(我可能使用了错误的流程图元素..歉意)。
addMessage({ state }, { msg, selfHash }) {
let addAsNewMsg = true;
const lastMessage = state.messages.slice(-1)[0];
if (lastMessage && lastMessage.userHash === msg.userHash) {
// The last message was also sent by the same user
// Check if it arrived within the grouping threshold duration (60s)
const lastMessageTime = moment(lastMessage.time);
const msgTime = moment(msg.time);
const diffSeconds = msgTime.diff(lastMessageTime, "seconds");
if (diffSeconds <= 60) {
addAsNewMsg = false; // We're going to be appending.. so
lastMessage.message.push(msg.message);
// We're going to now update the timestamp and (any) other fields.
delete msg.message; // Since, we've already added this above
Object.assign(lastMessage, msg); // Update with any remaining properties
}
}
if (addAsNewMsg) {
state.messages.push(msg);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句