我正在尝试按日期对消息进行分组,例如在Facebook Messenger中。我出错了 [Vue警告]:组件渲染函数中可能有无限的更新循环
这里是JSFiddle,用于简单代码。
var app = new Vue({
el: "#app",
data: {
messages: [
{
content: "Hello",
position: "left",
created_at: 1551437421000
},
{
content: "Hi",
position: "right",
created_at: 1551437421000
},
{
content: "How are you",
position: "left",
created_at: 1551523821000
},
{
content: "I'm fine",
position: "right",
created_at: 1551610221000
},
{
content: "Nice to meet you!",
position: "right",
created_at: 1551610221000
},
{
content: "How's going?",
position: "left",
created_at: 1551869421000,
},
{
content: "Fine",
position: "right",
created_at: 1551869421000
},
],
temp: {
old_unique_date: null
}
},
methods: {
groupByDate(date){
var old_date = this.temp.old_unique_date;
var new_date = new Date(date).getDate();
if(old_date != new_date){
this.temp.old_unique_date = new_date;
var day = ("0" + new Date(date).getDate()).slice(-2);
var month = ("0" + (new Date(date).getMonth() + 1)).slice(-2);
var date_data = day +"/"+ month;
return date_data;
}else{
return "";
}
}
}
})
.message {
background: lightblue;
padding: 10px 20px;
margin: 10px 0;
max-width: 60%;
border-radius: 10px;
}
.left {
float: left;
margin-left: 10px;
}
.right {
float: right;
margin-right: 10px;
}
.chat_room {
position: relative;
}
.date {
text-align: center;
color: red;
}
.c_f {
clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
<div class="chat_room">
<div v-for="message in messages">
<div class="date" v-html="groupByDate(message.created_at)">
</div>
<div class="message" :class="message.position">
{{message.content}}
</div>
<div class="c_f"></div>
</div>
</div>
</div>
您可以看到红色日期。 created_at是发送消息的日期。当消息是在01/03发送时,对于所有发送日期为01/03的消息,我只想显示一个01/03。看来还可以。但这有一个控制台错误,称为“ [Vue警告:您可能在组件渲染函数中有一个无限的更新循环。”