尝试在 Vuejs 中过滤数组时出现问题?

Issue when trying to filter array in Vuejs?

data() {
    return {
      searchString: '',
      sortKey: 'name',
      checked: false,
      Item,
      items: [{
        price: '1',
        name: 'mm'
      }, ],

      computed: {
        computedItems() {
          return this.items.map((item, index) => {
            item.key = `item_${index}`
            return item
          })
        },
        index: function() {
          let searchString = this.searchString
          let itemsClone = [...this.items] // Change added
          const sortedArray = itemsClone.sort((a, b) => {
            if (a[this.sortKey] < b[this.sortKey]) return -1
            if (a[this.sortKey] > b[this.sortKey]) return 1
            return 0
          })
          if (!searchString) {
            return sortedArray
          } else {
            searchString = searchString.trim().toLowerCase()
            const search_array = sortedArray.filter((items) => {
              if (items.name.toLowerCase().indexOf(searchString) !== -1) {
                return items
              }
            })
            return search_array
          }
        }
      }
    <div class="wrapper">
      <input
        type="text"
        v-model="searchString"
        placeholder="search items from here"
      />
      <br />

      <virtual-list
        class="list"
        style="height: 360px; overflow-y: auto"
        data-key="key"
        :keeps="20"
        :data-sources="computedItems"
        :data-component="Item"
      />
      <hr />
    </div>

尝试在 Vuejs 中过滤数组时出现问题?

我可以呈现项目列表,但问题是无法过滤数组文件。我在我的输入搜索字段中使用了 v-model,然后将 computed 属性 写入其中,但我仍然收到错误

我可以在我的搜索输入中使用 v-model 并过滤数据吗???

更新了 sandbox 代码以根据输入过滤项目。

computedItems() {
  let initItems = this.items.map((item, index) => {
    item.key = `item_${index}`
    return item
  })

  return initItems.filter((item) => item.name.includes(this.filterValue))
},

检查你的.filter()函数

检查右下角控制台右侧的“问题”选项卡:

  • Expected to return a value at the end of arrow function. (array-callback-return)

实现如下所示:

const search_array = sortedArray.filter((items) => {
  if (items.name.toLowerCase().indexOf(searchString) !== -1) {
    return items
  }
})

所以过滤函数会像这样工作:

const search_array = sortedArray.filter((item) => {
  return item.name.toLowerCase().indexOf(searchString) !== -1;
});

如果应该保留物品,而不是物品本身,您应该 return true
JavaScript 将假设 items 是一个真实的值并且是有效的代码。这只是一个eslint警告,但这里是一个重要警告。

参见 .filter() 的文档:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

让你的搜索工作

您只是忘记使用正确的搜索值变量。
您在数据中将其命名为 filterValue,但 index 使用 this.searchString.
所以在 index() 的第一行修复这个:

let searchString = this.filterValue

如果您在模板中输出 {{ index }},您可以在输入时实时看到过滤后的数组。