gpt4 book ai didi

javascript - 如何在 Vuejs 中过滤具有多个条件的数组?

转载 作者:行者123 更新时间:2023-12-05 03:32:30 25 4
gpt4 key购买 nike

const app = new Vue({
el: '#app',
data: {
search: '',
itemsList: [],
isLoaded: false,
selectNum: status,
userList: [{
id: 1,
name: "Prem",
status: "ok"
},
{
id: 2,
name: "Chandu",
status: "notok"
},
{
id: 3,
name: "Shravya",
status: "ok"
},
{
id: 4,
name: "kirt",
status: "notok"
}
]
},
created() {
vm.itemsList = [];
vm.isLoaded = true;
},
computed: {
filteredAndSorted() {
// function to compare names
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}

return this.userList.filter(user => {
return user.name.toLowerCase().includes(this.search.toLowerCase()) &&
user.status === this.selectNum
}).sort(compare)
}
}
})
<div id="app">
<div v-if="isLoaded">
<select v-model="selectNum" name="text">
<option :value="status">ok</option>
<option :value="status">notok</option>
</select>
</div>
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title.." />
<label>Search Users:</label>
</div>
<ul>
<li v-for="user in filteredAndSorted">{{user.name}}</li>
</ul>
</div>

我正在努力实现这样的功能,

最初数组将在 v-for 的帮助下加载。在顶部,我有两个选项,称为搜索栏和下拉菜单。在那些人的帮助下,我正在尝试填充数组。

在使用搜索栏的地方,我想过滤数组值。使用下拉菜单,我想过滤每个数组中存在的状态。

最佳答案

尝试像下面的片段:

const app = new Vue ({
el: '#app',
data() {
return {
search: '',
itemsList: [],
isLoaded: false,
selectNum: '',
userList: [
{
id: 1,
name: "Prem",
status:"ok"
},
{
id: 2,
name: "Chandu",
status:"notok"
},
{
id: 3,
name: "Shravya",
status:"ok"
},
{
id: 4,
name: "kirt",
status:"notok"
}
]
}
},
created(){
this.isLoaded = true;
},
computed: {
filteredAndSorted(){
function compare(a, b) {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
}
const res = this.userList.filter(user => {
return user.name.toLowerCase().includes(this.search.toLowerCase())
}).sort(compare)
if (this.selectNum) {
return res.filter(user => user.status === this.selectNum )
}
return res
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div v-if="isLoaded">
<select v-model="selectNum" name="text">
<option value="" selected="selected">Select status</option>
<option value="ok">ok</option>
<option value="notok">notok</option>
</select>
</div>
<div class="search-wrapper">
<input type="text" v-model="search" placeholder="Search title.."/>
<label>Search Users:</label>
</div>
<ul>
<li v-for="user in filteredAndSorted">{{user.name}}</li>
</ul>
</div>

关于javascript - 如何在 Vuejs 中过滤具有多个条件的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70470193/

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