Vue.js中使用Axios获取API数据后按公司筛选产品的实现求助
Hey there! Let's work through adding company-based filtering to your filterProducts method—here's a step-by-step breakdown with actionable tips:
First, Let's Reframe Your Current Method
Right now, you're fetching products and directly assigning them to this.products. The key fix is adding a filtering step after you receive the data (inside the .then() callback), before updating your state.
Step 1: Define Your Filter Criteria
First, clarify what "company information" you're filtering by—this could be a company ID, name, or another unique field. Make sure you know the exact structure of the product objects returned by your API (e.g., does each product have a companyId property, or a nested company.name field?).
To make this flexible, pass your target company info as a parameter to filterProducts instead of hardcoding it.
Step 2: Add the Filter Logic
Use JavaScript's Array.filter() method to narrow down the product list. Here's how to modify your method:
filterProducts(targetCompany) { axios.get("http://fake-api.ns.nsdevel.eu/products") .then((resp3) => { // Filter products to match your company criteria const filteredProducts = resp3.data.products.filter(product => { // Replace this with your actual matching logic // Examples: // Match by company ID: return product.companyId === targetCompany.id; // Match by company name (case-insensitive): return product.company.name.toLowerCase() === targetCompany.name.toLowerCase(); return product.companyId === targetCompany.id; }); // Update state with filtered results this.products = filteredProducts; // Optional: Handle empty results if (filteredProducts.length === 0) { this.errorMessage = "No products found for this company."; } else { this.errorMessage = ""; // Clear any previous error } }) .catch((error) => { this.errorMessage = error.message; console.error("There was an error!", error); }); }
Common Pitfalls to Check
- Mismatched field names/structure: If filtering isn't working, first log a single product to confirm the field exists:
This will reveal if you're trying to accessconsole.log("Sample product:", resp3.data.products[0]);product.companyIdwhen the field is actuallyproduct.company.id, for example. - Type mismatches: If your API returns
companyIdas a number but you're passing a string, convert types to match (e.g.,Number(targetCompany.id)). - Case sensitivity: When filtering by text (like company names), use
.toLowerCase()or.toUpperCase()to avoid missing matches.
Bonus: Clean Up Your Code
For better maintainability, extract the filtering logic into a separate function:
// Reusable filter function filterProductsByCompany(products, targetCompany) { return products.filter(product => { return product.companyId === targetCompany.id; }); } // Updated fetch method filterProducts(targetCompany) { axios.get("http://fake-api.ns.nsdevel.eu/products") .then((resp3) => { const filtered = this.filterProductsByCompany(resp3.data.products, targetCompany); this.products = filtered; this.errorMessage = filtered.length === 0 ? "No products found for this company." : ""; }) .catch((error) => { this.errorMessage = error.message; console.error("There was an error!", error); }); }
内容的提问来源于stack exchange,提问作者blackrox

