gpt4 book ai didi

javascript - 无法过滤Vue js中的对象数组

转载 作者:行者123 更新时间:2023-11-28 17:31:21 25 4
gpt4 key购买 nike

我想按类型过滤游戏。 pdList 是对象(游戏)的数组。为此,我使用 Array.filter()。但它不起作用。下面是代码。如果我的方法错误,请纠正我。它在控制台中也没有给出任何错误。

Vuejs 代码:

new Vue({
el: "#app",
data: {
currentFilter:"all",
pdList:[,
{
"title": "Double Dragon: Neon",
"url": "/games/double-dragon-neon/xbox-360-131320",
"platform": "Xbox 360",
"score": 3,
"genre": "Fighting",
"editors_choice": "N",
"release_year": 2012
},
{
"title": "Guild Wars 2",
"url": "/games/guild-wars-2/pc-896298",
"platform": "PC",
"score": 9,
"genre": "RPG",
"editors_choice": "Y",
"release_year": 2012
}]
},
methods: {
filterByGenre:function(filterby){
this.currentFilter = filterby;
},
filteredGames:function(pdList){
console.log("inside filtergames");
if(this.currentFilter == "all"){

return pdList;
}else{
return pdList.filter(function(game){
console.log(this.currentFilter);
return game.genre == this.currentFilter;
});
}
}
}
})

HTML

<div id="app">
<h2>Game Lister:</h2>
<ol>
<li v-for="game in filteredGames(pdList)">

{{game.genre}}

</li>
</ol>
</div>

<select v-model="currentFilter">
<option value="all">all</option>
<option value="Platformer">Platformer</option>
<option value="Platformer">Puzzle</option>
<option value="Platformer">Sports</option>
<option value="Platformer">Strategy</option>

</select>

最佳答案

这个想法并不正确。代码中的一些缺陷:

在模板中:

  1. 选择选项超出 div#app - 将导致选择不显示
  2. 除了“all”之外的所有选项在 select 中具有相同的值

在 View 模型中:

    data() 中的
  1. pdList[, 开头 - 这会破坏代码
  2. 一个简单的计算函数即可完成这一切 - 并且您尚未使用模板中使用的任何方法

解决方案是:

模板

<div id="app">
<h2>Game Lister:</h2>
<ol>
<li v-for="game in filteredGames">{{game.title}}</li>
</ol>

<select v-model="currentFilter">
<option value="all">all</option>
<option value="Fighting">Fighting</option>
<option value="RPG">RPG</option>
</select>
</div>

View 模型

data: {
currentFilter: "all",
pdList: [{
"title": "Double Dragon: Neon",
"url": "/games/double-dragon-neon/xbox-360-131320",
"platform": "Xbox 360",
"score": 3,
"genre": "Fighting",
"editors_choice": "N",
"release_year": 2012
}, {
"title": "Guild Wars 2",
"url": "/games/guild-wars-2/pc-896298",
"platform": "PC",
"score": 9,
"genre": "RPG",
"editors_choice": "Y",
"release_year": 2012
}]
},
computed: {
filteredGames () {
const self = this;
if (self.currentFilter === 'all') {
return self.pdList;
} else {
return self.pdList.filter(function(game) {
return self.currentFilter === game.genre;
});
}
}
}

关于javascript - 无法过滤Vue js中的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50343126/

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