【问题标题】:Vue.js remove always last item from arrayVue.js 总是从数组中删除最后一项
【发布时间】:2017-05-27 10:11:05
【问题描述】:

我正在尝试使用一个简单的过滤器,当我单击“添加过滤器”按钮时,我将复制过滤器并将其添加到带有过滤器的数组中。添加没有问题,但我无法删除(十字图标)正确的输入 - 我总是从数组中删除最后一项而不是正确的一项。我有这个代码:

<div class="container">

  <div class="jumbotron">
    <div>
      <div class="form-group">
        <input type="text" class="form-control input-sm" id="pref-search">
      </div>
      <div class="form-group">
        <button type="button" class="btn btn-default filter-col btn-sm" v-on:click="addFilter">
          <i class="fa fa-plus-circle" aria-hidden="true"></i> Add filter
        </button>
      </div>
    </div>

    <div v-for="filter in extFilters.filters" style="margin: 10px 0">
      <div class="form-group">
        <input type="text" class="form-control input-sm" id="pref-search">
      </div>
      <div class="form-group">
        <button type="button" class="btn btn-default filter-col btn-sm" v-on:click="addFilter">
          <i class="fa fa-plus-circle" aria-hidden="true"></i> Add filter
        </button>
        <span v-on:click="removeFilter(filter)"><i class="fa fa-times" aria-hidden="true"></i></span>
      </div>
    </div>
  </div>
</div>

这里是 Vue.js:

var data = {
  'filters': [],
}

// app Vue instance
var app = new Vue({
  // app initial state
  data: {
    extFilters: data,
  },

  // methods that implement data logic.
  methods: {
    addFilter: function() {
      this.extFilters.filters.push({
        andor: 'a',
        search_in: '',
        operator: '',
        text: ''
      })
    },

    removeFilter: function(filter) {
      var index = this.extFilters.filters.indexOf(filter);
      this.extFilters.filters.splice(index, 1);
    },
  },
})

// mount
app.$mount('.jumbotron')

问题是当我添加三个过滤器并且我想删除第一个过滤器时,它将始终删除最后一个过滤器。为什么会发生或我做错了什么?

这是我在jsFiddle 上的问题。最佳答案也在 jsFiddle 中。

【问题讨论】:

  • 因为你使用 var index = this.extFilters.filters.indexOf(filter); ,总是从列表中返回第一个过滤器。更改 indexOf() 函数

标签: javascript arrays vue.js splice vuejs2


【解决方案1】:

正确答案是……https://jsfiddle.net/mariaczi/hed0ew5o/1/

您没有在文本输入中添加v-model='filter.text',这会使您的所有过滤器看起来都一样,这就是它不起作用的原因。

现在工作正常。

希望对你有帮助。

【讨论】:

  • 可能值得更新小提琴以反映原来的 removeFilter function 按实现方式工作,并且缺少绑定是唯一的问题。
猜你喜欢
  • 2020-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-01
  • 1970-01-01
  • 2020-07-07
  • 1970-01-01
相关资源
最近更新 更多