Vue3数组筛选无结果:勾选分类复选框后无对应帖子显示
问题原因与解决方法
你的筛选函数里的filter回调函数没有返回判断结果。当你使用多行箭头函数(内部包含console.log语句)时,必须显式添加return语句来返回判断值;否则回调函数默认返回undefined,而undefined在filter逻辑中会被视为false,导致所有帖子都被过滤掉,最终页面无内容显示。
修正后的代码
function filterPosts() { filtered.value = posts.value; if (visibleList.value.length != 0) { filtered.value = filtered.value.filter((e) => { const isMatch = visibleList.value.includes(e.category); console.log(isMatch); return isMatch; // 显式返回判断结果 }); } else { filtered.value = posts.value; } }
如果不需要打印日志,也可以简化为单行箭头函数(自动返回结果):
function filterPosts() { filtered.value = posts.value; if (visibleList.value.length != 0) { filtered.value = filtered.value.filter((e) => visibleList.value.includes(e.category) ); } else { filtered.value = posts.value; } }
内容的提问来源于stack exchange,提问作者crawlingdev
相关产品推荐
相关产品推荐

