简体   繁体   中英

Vue.js remove always last item from array

I'm trying to have a simple filter where when I click on button "add filter" I will duplicate filter and it will add to array with filters. There is no problem to add but then I cannot remove (cross icon) the right input - I always remove the last item from array instead the right one. I have this code:

<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>

And here is 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')

Problem is when I add for example three filters and I would like to remove first filter then it will remove always the last one. Why it is happening or what I'm doing wrong?

Here is my problem on jsFiddle . Best answer would be also in jsFiddle.

Correct answer is... https://jsfiddle.net/mariaczi/hed0ew5o/1/

You did not add v-model='filter.text' to the text input which makes all your filters looking the same, that's why it was not working.

Working properly now.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM