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,然后將計算屬性寫入其中,但仍然出現錯誤
下面是我的代碼
https://codesandbox.io/s/live-demo-virtual-list-forked-hwq38?file=/src/App.vue
我可以在搜索輸入中使用 v-model 并過濾資料嗎???
uj5u.com熱心網友回復:
檢查您的.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;
});
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 }}在模板中輸出,則可以在鍵入時實時查看過濾后的陣列。
uj5u.com熱心網友回復:
使用代碼更新沙箱以根據輸入過濾專案。
computedItems() {
let initItems = this.items.map((item, index) => {
item.key = `item_${index}`
return item
})
return initItems.filter((item) => item.name.includes(this.filterValue))
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/373162.html
下一篇:文本中的粗體字
