javascript - VueJS v-for loop breaking when array values are equal to each other - Stack Overflow

my pen: html<template v-for="spot in bars" :key="item.$index"><div id=&quo

my pen:

html

    <template v-for="spot in bars" :key="item.$index">
      <div id="bar-holder">
    <div class="bars">
      <ul>
        <span>{{ $index }}</span>
        <li v-for="n in bars[$index]"></li>
      </ul>
      <button v-on:click="increase($index)">+</button>
    </div>
  </div>
  </template>

javascript

var par = {
  bars : [ 1, 5, 6 ]
}
var cl = new Vue({
  el: '#container',
  data: par,
  methods: {
    increase: function (index) {
      var value = this.bars[index];
      value++;
      par.bars.$set(index, value);
    },
  }
})

So whenever you click the increase button under each group of bars, that value in the par.bars array increases. For some reason, whenever par.bar[index]'s value equals that of one of its siblings, one of the bar elements disappears.

I've went over my code for about an hour now, and cannot figure out where this is breaking.

my pen: http://codepen.io/leetzorr/pen/aprZqO

html

    <template v-for="spot in bars" :key="item.$index">
      <div id="bar-holder">
    <div class="bars">
      <ul>
        <span>{{ $index }}</span>
        <li v-for="n in bars[$index]"></li>
      </ul>
      <button v-on:click="increase($index)">+</button>
    </div>
  </div>
  </template>

javascript

var par = {
  bars : [ 1, 5, 6 ]
}
var cl = new Vue({
  el: '#container',
  data: par,
  methods: {
    increase: function (index) {
      var value = this.bars[index];
      value++;
      par.bars.$set(index, value);
    },
  }
})

So whenever you click the increase button under each group of bars, that value in the par.bars array increases. For some reason, whenever par.bar[index]'s value equals that of one of its siblings, one of the bar elements disappears.

I've went over my code for about an hour now, and cannot figure out where this is breaking.

Share asked Feb 17, 2017 at 16:46 justinhurstjustinhurst 151 silver badge3 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

Replace

<template v-for="spot in bars" :key="spot.$index">

with:

<template v-for="spot in bars" :key="spot.$index" track-by="$index">

Explanation in the Vue.js guide: http://v1.vuejs/guide/list.html#track-by-index

This is because Vue reuse templates with same key.

To avoid that you could use index as key (apparently that was you were trying to do in first place!)

Change your template's directive v-for to something like this

<template v-for="spot in bars.length">

Please see this working fiddle

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745044058a4607987.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信