我有一个对象数组,要列出该月份的标题。并不是循环中的每个对象都有标题,只有顺序对象中的月份发生变化时,才会显示标题
例如,对象可能看起来像
data [
{date:'January', info: 'some other data'},
{date:'January', info: 'some other data'},
{date:'February', info: 'some other data'},
{date:'February', info: 'some other data'},
{date:'March', info: 'some other data'},
{date:'March', info: 'some other data'},
];
循环看起来像这样
<div v-for="d in data" :heading="getDate(d.date)" >
{{ heading }}
<p> {{ d.info }}</p>
</div>
showDate函数位于“引擎盖”部分
data() {
return {
currentmonth: ""
}
},
methods: {
getDate(date) {
if (date != this.currentmonth) {
this.currentmonth = date
return "<h2>" + date + "</h2>"
} else {
return ""
}
}
所以我只想在循环中的对象之间的日期更改时显示H2,所以出来的就是
<div>
<h2>January<h2>
<p>some other data</p>
</div>
<div>
<p>some other data</p>
</div>
<div>
<h2>February<h2>
<p>some other data</p>
</div>
<div>
<p>some other data</p>
</div>
<div>
<h2>March<h2>
<p>some other data</p>
</div>
<div>
<p>some other data</p>
</div>
但是我一直得到的结果是
[Vue warn]: You may have an infinite update loop in a component render function.
显然是因为我的getDate检查了vm中的日期,并且还从同一函数更新了日期。我已经尝试过观察者,计算属性,但无法弄清楚这一点。
答案 0 :(得分:0)
我认为您应该调整渲染,以免在实际渲染时尝试做太多的逻辑。而不是将日期列表交给Vue,而是让它弄清楚如何在渲染中对它们进行分组,预先计算分组的日期,然后让Vue渲染分组。
from .pokemon import IDfromPokemon
from .pokemon import PokemonfromID
from .pokemon import PokemonLearnset
from .pokemon import PokemonLocations
from .pokemon import PokemonTypes
from .pokemon import PokemonSprite
from .pokemon import ShinyPokemonSprite
from .pokemon import PokemonAbilities
from .pokemon import Pokemon
function contiguify(arr) {
const contiguousArr = [];
for (const d of arr) {
const lastMonthAdded = contiguousArr.length ?
contiguousArr[contiguousArr.length - 1].date :
null;
if (!lastMonthAdded || d.date !== lastMonthAdded) {
contiguousArr.push({
date: d.date,
infos: [
d.info
]
});
} else {
contiguousArr[contiguousArr.length - 1].infos.push(d.info);
}
}
return contiguousArr;
}
const app = new Vue({
el: "#app",
data() {
return {
dates: [{
date: 'January',
info: 'some other data'
},
{
date: 'March',
info: 'some other data'
},
{
date: 'January',
info: 'some other data'
},
{
date: 'February',
info: 'some other data'
},
{
date: 'February',
info: 'some other data'
},
{
date: 'March',
info: 'some other data'
},
{
date: 'March',
info: 'some other data'
},
{
date: 'February',
info: 'some other data'
},
{
date: 'March',
info: 'some other data'
},
{
date: 'March',
info: 'some other data'
}
]
};
},
computed: {
contiguousDates() {
return contiguify(this.dates);
}
}
});
答案 1 :(得分:0)
最后,我通过将数组索引传递给for循环来解决此问题,然后使用当前索引和上一个索引来比较日期。如果它们不同,我将其打印出来。