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,然后将计算属性写入其中,但我仍然遇到错误
我可以在我的搜索输入中使用 v-model 并过滤数据吗???
最佳答案
检查你的.filter()
函数
检查右下角控制台右侧的“问题”选项卡:
期望在箭头函数结束时返回一个值。 (数组回调返回)
实现看起来像这样:
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;
});
如果项目应该被保留,你应该返回 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 }}
,您可以在输入时实时看到过滤后的数组。
关于javascript - 尝试在 Vuejs 中过滤数组时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70214286/