从 Id Vuejs 过滤的数组中删除对象

Remove object from array filtered by an Id Vuejs

我正在执行一项功能,根据选中的复选框删除多条记录,但当我收到 ID(不是完整的对象)时,我遇到了将其从数组中删除的问题。

有人可以帮助我吗?

JSBin

JS:

new Vue({

  el: 'body',

  data: {
    record: {},
    selected: [],
    list: [
        { name: 'Google', id: 1, cat: 'Category 1' },
        { name: 'Facebook', id: 2, cat: 'Category 2' },
      ],
  },

  methods: {
    deleteSelected: function () {
      for (var r in this.selected) {
        this.list = this.list.filter(function(val, i) {
          return val.id !== this.selected[r];
        });
      }
    }
  }

});

HTML:

<body>

  <div class="container">

    <div class="row p-10">
      <div class="col-md-6 m_md_bottom_15">
        <span class="btn btn-danger" data-toggle="tooltip" data-original-title="Delete" @click="deleteSelected()">Remove selected</i></span>
      </div>
    </div>
  <hr>
   <table class="table table-striped table-bordered">
     <thead>
       <tr>
         <th></th>
         <th>Id</th>
         <th>Name</th>
         <th>Actions</th>
       </tr>
     </thead>
     <tbody>
       <tr v-for="r in list">
         <td><input type="checkbox" v-model="selected" value="{{ r.id }}"></td>
         <td class="text-center" style="width:90px"> {{ r.id }} </td>
         <td> {{ r.name }} </td>
         <td class="text-center" style="width:90px">
           <span class="btn btn-warning btn-xs" @click="edit(r)"><i class="fa-fw fa fa-pencil"></i></span>
         </td>
       </tr>
     </tbody>
  </table>
  </div>

  <div class="container">
    <pre>{{ $data | json }}</pre>
  </div>


  <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.20/vue.min.js"></script>
</body>

你的代码有两个主要问题,JS Bin 已经强调了其中之一:

  1. 如果函数引用循环值,则不应在循环内定义函数。 See here why.(除非你将它包装在 IIFE 中或使用 let 来定义你的循环变量)。

  2. 您正在使用 !== 运算符比较 Number 类型的 ID 和 String 类型的选定条目。 This wont work, because !== does a strict equal.(您可以在 container 输出中看到)。

为了解决第一个问题,我将完全放弃外部 for 循环并使用 indexOf 来检查 this.selected 中是否存在当前 val.id

this.selected.indexOf(val.id) === -1;

这还行不通,因为我们仍在比较 StringindexOf 中的 Number。所以我们必须将 val.id 转换为字符串(这解决了问题 #2)。

this.selected.indexOf(val.id.toString()) === -1;

这给我们留下了以下代码(在删除 for 循环之后):

new Vue({

  el: 'body',

  data: {
    record: {},
    selected: [],
    list: [
        { name: 'Google', id: 1, cat: 'Category 1' },
        { name: 'Facebook', id: 2, cat: 'Category 2' },
      ],
  },

  methods: {
    deleteSelected: function () {
        this.list = this.list.filter(function(val, i) {
            return this.selected.indexOf(val.id.toString()) === -1;
        }, this);
     }
  }

});

注意:为了在filter函数内部使用vue组件的this上下文,we pass it in as the second argument.

JS Bin