Vue.js中对象数组过滤失效问题排查及代码修正请求
解决Vue.js游戏列表按类型过滤无效的问题
我来帮你排查并修复代码里的问题,你的过滤功能失效主要有几个关键原因,咱们一步步来解决:
1. 数组初始化的语法错误
你的pdList数组开头多了一个逗号:
pdList:[, { "title": "Double Dragon: Neon", ... }]
这个多余的逗号会导致数组第一个元素是undefined,可能引发后续渲染或过滤的异常,需要把它删掉。
2. 过滤函数中this指向丢失的问题
在filteredGames方法里的pdList.filter()回调中,普通的function函数会改变this的指向,导致this.currentFilter无法访问到Vue实例里的属性。解决这个问题有三种常用方式:
- 使用箭头函数(推荐,箭头函数会继承外部的
this) - 在回调外先把
this存为变量(比如const self = this) - 给回调函数绑定
this(用.bind(this))
3. select选项的value值错误
你的HTML里所有<option>的value都写的是"Platformer",这会导致不管选哪个选项,currentFilter都会变成"Platformer",完全起不到过滤作用,需要把每个选项的value改成对应的类型值。
4. 推荐使用计算属性替代方法
你现在用方法filteredGames来返回过滤后的列表,每次组件渲染时方法都会重新执行,而使用计算属性会有缓存,只有当依赖的currentFilter或pdList变化时才会重新计算,性能更好。
修正后的完整代码
Vue.js代码
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 } ] }, // 用计算属性替代方法 computed: { filteredGames() { if (this.currentFilter === "all") { return this.pdList; } else { // 使用箭头函数保证this指向Vue实例 return this.pdList.filter(game => game.genre === this.currentFilter); } } }, methods: { filterByGenre(filterby) { this.currentFilter = filterby; } } })
HTML代码
<div id="app"> <h2>Game Lister:</h2> <!-- 注意v-for里直接用计算属性filteredGames --> <ol> <li v-for="game in filteredGames" :key="game.url"> {{ game.title }} - {{ game.genre }} </li> </ol> <select v-model="currentFilter"> <option value="all">all</option> <option value="Fighting">Fighting</option> <option value="RPG">RPG</option> <option value="Platformer">Platformer</option> <option value="Puzzle">Puzzle</option> <option value="Sports">Sports</option> <option value="Strategy">Strategy</option> </select> </div>
另外我还加了:key="game.url"在v-for里,这是Vue的最佳实践,帮助Vue高效地更新列表。同时把选项里补充了你的游戏数据里有的Fighting和RPG类型,这样选中它们时能看到对应的过滤效果。
内容的提问来源于stack exchange,提问作者spratap124
相关产品推荐
相关产品推荐

