gpt4 book ai didi

javascript - 如何使用 Vue 搜索排序列表中的多个属性

转载 作者:搜寻专家 更新时间:2023-10-30 22:34:21 25 4
gpt4 key购买 nike

我有一个包含人们名字和姓氏的数据集,我希望用户能够使用 Vue 2 搜索这些数据。

到目前为止,我设法先按名字对列表进行排序,然后使用 Lodash 按姓氏对列表进行排序,并且我还设法按类型对它们进行分类。现在我想过滤/搜索(我不知道正确的词)数组,只显示名字或姓氏(或两者的一部分)与输入字段的内容匹配的人。

vanilla JS 解决方案与 Lodash 解决方案一样受欢迎!

props: {
people: {
type: Array,
required: true
}
},

data: function(){
return {
filter: '',
people:[{
"FirstName" : "Stefan",
"LastName" : "Braun",
"Type" : "EN",
},
{
"FirstName" : "Jenny",
"LastName" : "Smith",
"Type" : "VO",
},
{
"FirstName" : "Susan",
"LastName" : "Jones",
"Type" : "EN",
}]
}
}

methods: {

matchingType: function (people, type) {
people = this.alphabeticallyOrdered(this.searchFiltered(people))

return people.filter(function (person) {
return person.Type == type
})
},

alphabeticallyOrdered: function(arr){
return _.orderBy(arr, ['FirstName', 'LastName'])
},

searchFiltered: function(arr){
filter = this.filter
return _.some(arr, _.unary(_.partialRight(_.includes, this.filter)));
}
},

template: `
<div>
<input type="text" model="filter"></input>
<div v-for="type in types" class="type" :class="type.short">
<h2 class="type-name">{{type.long}}</h2>
<div class="people">
<div v-for="person in matchingType(people, type.short)" class="person">
<div class="personal-details">
<p class="h2">{{person.FirstName}}</p>
<p class="h4">{{person.LastName}}</p>
</div>
</div>
</div>
</div>
</div>
`

最佳答案

通常您会使用 computed property 来处理这个问题.

这是一个例子。我在你的例子中消除了很多额外的代码,因为有些部分我无法在不知道你在做什么的情况下复制(你没有发布组件的填充代码),但本质上,你会写一个计算如下所示的属性并在您的模板中对其进行迭代。

console.clear()

new Vue({
el: "#app",
data:{
people:[{
"FirstName" : "Stefan",
"LastName" : "Braun",
"Type" : "EN",
},
{
"FirstName" : "Jenny",
"LastName" : "Smith",
"Type" : "VO",
},
{
"FirstName" : "Susan",
"LastName" : "Jones",
"Type" : "EN",
}],
filterText: null
},
computed:{
filteredPeople(){
// If there is no filter text, just return everyone
if (!this.filterText) return this.people

// Convert the search text to lower case
let searchText = this.filterText.toLowerCase()

// Use the standard javascript filter method of arrays
// to return only people whose first name or last name
// includes the search text
return this.people.filter(p => {
// if IE support is required and not pre-compiling,
// use indexOf instead of includes
return p.FirstName.toLowerCase().includes(searchText) ||
p.LastName.toLowerCase().includes(searchText)
})
}

}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.min.js"></script>
<div id="app">
<input type="text" v-model="filterText">
<ul>
<li v-for="person in filteredPeople">
{{person.FirstName}} {{person.LastName}}
</li>
</ul>
</div>

关于javascript - 如何使用 Vue 搜索排序列表中的多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47679814/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com