Vue3计算属性过滤对象报is not a function错误的正确处理方案
错误根源
你遇到的所有报错本质都是在非数组类型的变量上调用了仅数组支持的方法:
filter is not a function:this.colours.allCatalogModelColours是对象类型,只有数组支持filter方法findIndex is not a function/读取any/some报错:从你给出的结构可以看到,每个条目的model字段是单个对象,不是数组,不需要调用遍历方法,直接读取model.modelName判断匹配即可
正确实现
场景1:返回筛选后的数组(和你最初的需求一致)
colorByModel() { const objectColours = this.colours.allCatalogModelColours; // 先提取对象的所有值转为数组,再过滤 return Object.values(objectColours).filter(item => { // 可选链?.用于避免个别条目无model字段时报错 return item.model?.modelName === "ModelThree"; }); }
场景2:需要保留原对象的键,返回对象格式结果
colorByModel() { const objectColours = this.colours.allCatalogModelColours; const result = {}; Object.entries(objectColours).forEach(([key, item]) => { if (item.model?.modelName === "ModelThree") { result[key] = item; } }); return result; }
内容的提问来源于stack exchange,提问作者druj_nasu
相关产品推荐
相关产品推荐

