首页 > 解决方案 > Vue - 过滤 2D 数组但修改原始未过滤数组 v-models

问题描述

我有一个对象数组,每个对象有 7 个键,每个键包含一个对象。GB,GI,DE 是对象的键 示例:

foo[0] contains {
GB:  { example: "example" , example1: "example1"},
FI:  { example: "example" , example1: "example1"},
DE:  { example: "example" , example1: "example1"},
ETC,ETC
}

我正在输出这个带有 v-for 的二维数组,在 v-for 内部,我有选择选项和文本字段等来操作数组中的数据。因此,每个选择选项或文本字段都有一个分配给当前元素索引的 v-model,以便能够操作数组的数据。

现在我想添加一个搜索栏来搜索特定元素。这可以通过添加一个过滤器并遍历这个过滤数组中的项目来完成。但是,如果我这样做,我将无法操作原始数组中的数据,因为新的过滤数组将具有不同的索引

请问我该如何解决?

提前致谢!

标签: javascriptarraysvue.jsfilter

解决方案


在 JavaScript 中,对象是一种引用类型,因此您可以在新数组中使用它的引用,然后对其进行变异。

<div id='app'>
  <input v-model='search'>
  <div v-for='item in filteredItems'>
    <label>{{ item.name }}</label>
    <input v-model='item.input'>
  </div>
</div>
new Vue({
  data: {
    search: '',
    items: [
      {
        name: 'maculomancy',
        input: 'divination using spots'
      },
      {
        name: 'forficulate',
        input: 'like scissors'
      },
      {
        name: 'wainage',
        input: 'cultivation of land'
      }
    ]
  },
  computed: {
    filteredItems() {
      return this.items.filter(item =>
        new RegExp(this.search, 'i').test(item.name)
      )
    }
  }
}).$mount('#app')

例子


推荐阅读