使用Vue JS复制输入字段,增加索引

aUsing Vue JS to duplicate an input field, incrementing the index

本文关键字:增加 索引 字段 输入 Vue JS 复制 使用      更新时间:2023-09-26

我需要复制一个文本输入字段,当用户单击按钮"添加另一个",并增加新字段上的索引。它和另一个问题很相似但是解没有增加任何东西。

复制字段并增加索引,但它影响所有索引,而不仅仅是最新的索引。(感谢Roy J的提示)

这是我的模板:

<div id="app">
  <template v-for="slot in timeslots">
    <div><input type="text" name="performances[@{{ count }}][timestamp]" v-model="slot.timestamp" placeholder="index @{{ count }}"></div>
  </template>
  <span class="add green btn" @click="addAnother"><i class="fa fa-plus-circle"></i> Add another</span>
  <pre>@{{ timeslots | json }}</pre>
</div>

这是我在Vue JS中的内容:

new Vue({
  el: '#app',
  data: {
      timeslots: [
          {
            timestamp: '',
            count: 0
          }
      ],
      count: 0
  },
  methods: {
    addAnother: function(){
      this.timeslots.push({
        timestamp: '',
        count: this.count++
      });
    }
  }
});

它适用于我,如果我只是合格的count++this。我将其设置为预增量,以避免使第一个元素重复。

我已经更改了占位符文本,以引用slot.count(当前的count,而不是父count)。

new Vue({
  el: '#app',
  data: {
    timeslots: [{
      timestamp: '',
      count: 0
    }],
    count: 0
  },
  methods: {
    addAnother: function() {
      this.timeslots.push({
        timestamp: '',
        count: ++this.count
      });
    }
  }
});
.green.btn {
  background-color: green;
  color: white;
  padding: 5px;
}
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div id="app">
  <template v-for="slot in timeslots">
    <div>
      <input type="text" name="performances[@{{ slot.count }}][timestamp]" v-model="slot.timestamp" placeholder="index {{ slot.count }}">
    </div>
  </template>
  <span class="add green btn" @click="addAnother"><i class="fa fa-plus-circle"></i> Add another</span>
  <pre>@{{ timeslots | json }}</pre>
</div>