2016-12-30 62 views
2

我正在研究允许用户记录客户的时间表。 我想显示属于该月份的笔记组前的月份和年份。Vuejs:为变量赋值时的无限循环

例如:

February 2016 
"Note 4" - 2016-02-15 
"Note 3" - 2016-02-05 

January 2016 
"Note 2" - 2016-01-28 
"Note 1" - 2016-01-12 

,因为我用VueJS显示我的笔记,我想测试每一个音符,以检查是否一个月是从保存在一个名为“currentMonth”变量月份不同。 所以我使用了V-如果我显示了一个名为“isNewMonth”功能来检查值:

<div v-for="note in notes | orderBy 'date' -1" > 
    <div v-if="isNewMonth(note)"><% currentMonth %></div> 
    <div style="background-color: #<% note.type.color %>; margin-bottom: 10px; border-left: solid #<% note.type.border_color %> 5px; padding-left: 5px;"> 
     <p class="noteMessage"><% note.message %><p> 
     <p class="noteInfos">Par <% note.author %> le <% note.date %></p> 
    </div> 
</div> 

而且功能isNewMonth:

isNewMonth: function(note) { 
    var noteMonth = parseInt(note.date.split("-")[1]); 
    if(this.currentMonth != noteMonth) 
    { 
    this.$set('currentMonth', noteMonth); 
    return true; 
    } 
    else 
    { 
    return false; 
    } 
} 

我与行的问题“这个。$ set('currentMonth',noteMonth);“。当我添加这条线时,我陷入了无限循环。 每当我删除这条线时,一切都很好(但它总是显示每个音符前的月份)。

你知道解决我的问题的方法吗?

回答

1

我不确定无限循环,但不能用当前的方法做到这一点。

currentMonth是一个单变量,vueJs有双向数据绑定,我说的是,如果你改变currentMonth一次,它会在所有的地方改变。这不是说第一个循环会显示一个值,下一个循环会设置其他值。

它将始终显示最新值。

相反,你可以这样做以下:

<div v-for="(note, index) in notes | orderBy 'date' -1" > 
    <div v-if="hasMonthchanged(note, index)"><% getMonth(note) %></div> 
    <div style="background-color: #<% note.type.color %>; margin-bottom: 10px; border-left: solid #<% note.type.border_color %> 5px; padding-left: 5px;"> 
     <p class="noteMessage"><% note.message %><p> 
     <p class="noteInfos">Par <% note.author %> le <% note.date %></p> 
    </div> 
</div> 

其中hasMonthchanged是将返回蒙特是否已经改变

你可以只用最后一个音符比较功能,月份是否有变化。

+0

谢谢你的回答! 我没有考虑currentMonth的问题,当我这样做时我可能分心了^^ 它完美地工作=) –