You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 00:55:39