如何在vue js中从数组中删除选定的数据?

时间:2017-08-11 05:08:57

标签: javascript html vue.js vuejs2

我需要拼接数组中的数据,我已经使用了以下内容,

HTML:

           <div id="app">
                <select v-model="facilityAvailable" name="facilities" multiple="multiple" id="facilities" size="4" class="form-control">
                  <option v-for="availability in availableFacilities" v-bind:value="availability">{{availability.label}}--</option>
                </select>
                <a @click="removeFacilities" class="btn btn-default remove_option" rel="facilities2" id="remove"><i class="fa fa-arrow-left"></i></a>
                <a @click="addFacilities" class="btn btn-default add_option" rel="facilities2" id="add"><i class="fa fa-arrow-right"></i></a>
                <select v-model="facilitySelected" name="facilities" multiple="multiple" id="facilities2" size="4" class="form-control">
                  <option v-for="facility in selectedFacilities" v-bind:value="facility">{{facility.label}}</option>
                </select>

            </div>

脚本:

new Vue({
  el: "#app",
  data: {
   facilityAvailable: [],
      facilitySelected:[],
      availableFacilities: [{
        value: 0,
        label: 'Double (Non a/c)'
      },
      {
        value: 1,
        label: 'Premium Double (a/c)'
      },
      {
        value: 2,
        label: 'Standard Double (a/c)'
      }
    ],
    selectedFacilities: [],
  },
  methods: {
    removeFacilities() {
    this.availableFacilities = this.facilitySelected.concat(this.availableFacilities);
    this.selectedFacilities.splice(this.availableFacilities.value,1);
    },
    addFacilities() {
    this.selectedFacilities = this.facilityAvailable.concat(this.selectedFacilities);
    this.availableFacilities.splice(this.selectedFacilities.value,1);
    }
  }
})

在这里,我想将一个元素从一个选择框转移到另一个选择框,我已经使用concat添加到另一个选择框,splice用于删除该元素。一切都很好。但是当我splice时,它按照0,1,2的顺序进行拼接,我需要根据该特定元素的索引号进行拼接。明确地说,我可以按任何顺序选择和删除元素,需要删除该特定元素并将其转移到第二个选择框中,而现在如果我按顺序删除它,它的工作正常,但如果我改变顺序并拼接它不起作用。此外,当我选择多个元素并删除时,同样的事情发生了。请帮我解决这个问题。

小提琴链接是https://jsfiddle.net/pmvp3td6/9/

1 个答案:

答案 0 :(得分:1)

我不确定我是否理解你正在寻找的东西,但在你的addFacilities中试试:

 addFacilities() {
    let i = 0;
    for(i; i<this.facilityAvailable.length;i++){ 
        this.selectedFacilities.push(this.facilityAvailable[i]);
        this.availableFacilities = this.availableFacilities.filter(facilities => facilities.value != this.facilityAvailable[i].value);
    }
}

如果这是你想要的,你可以在删除部分

中做类似的事情