Vue3+Axios获取数据时,如何在filteredProducts中使用传入的Prop
解决方案:用传入的brand.name过滤Axios获取的数据
你可以直接将硬编码的'Nike'替换为this.brand.name,同时为了避免brand为空或name不存在时出现报错,建议加上可选链和默认值处理。如果后续传入的brand会动态变化,还需要监听brand的变化来重新过滤数据,以下是优化后的完整代码:
export default { data() { return { filteredProducts: [], allProducts: [] // 存储所有产品,避免重复请求接口 }; }, mounted() { axios .get('/src/stores/sneakers.json') .then(response => { this.allProducts = response.data; this.filterProducts(); // 初始执行过滤 }) }, methods: { filterProducts() { // 处理brand为空或name不存在的情况,默认用空字符串(不会匹配任何内容) const targetBrand = this.brand?.name || ''; this.filteredProducts = this.allProducts.filter(product => product.name.includes(targetBrand) ); } }, watch: { // 监听brand对象的变化,深度监听确保name更新时触发 brand: { deep: true, handler() { this.filterProducts(); } } }, computed: { resultCount() { // 数组直接取length,比Object.keys更高效 return this.filteredProducts.length; }, }, props: { brand: { type: Object, required: true, // 建议设为必填,确保组件使用时传入有效数据 default: () => ({ name: '' }) // 备选:给默认值避免无值报错 }, }, }
关键说明:
- 新增
allProducts存储所有接口返回的产品,后续brand变化时无需重新请求接口,直接复用数据 - 抽离
filterProducts方法统一处理过滤逻辑,便于维护和复用 - 使用
this.brand?.name可选链操作符,防止brand为null/undefined时抛出错误 - 通过
watch监听brand的变化,当传入的品牌更新时自动重新过滤产品 resultCount直接使用数组的length属性,比Object.keys(filteredProducts).length更简洁高效
内容的提问来源于stack exchange,提问作者chrisjarn
相关产品推荐
相关产品推荐

