Vue.js如何根据categoryID获取对应分类下的产品列表
问题排查
现有代码存在3个核心问题导致无法展示对应分类产品:
- 产品接口赋值错误:产品接口返回的列表字段为
products,但回调中错误写为this.product = response.data.product,变量名、字段名都少了s,导致存储产品列表的products变量始终为空数组。 - 模板语法错误:模板中写
v-for="product in products(category._id)",但products是data中定义的数组,不是可执行函数,无法传参调用。 - 缺少分类匹配逻辑:拉取全量产品后,没有筛选出和当前分类ID匹配的产品。
修复方案
1. 修改前端脚本逻辑
修正接口赋值错误,新增计算属性过滤当前分类下的产品,修改后代码如下:
<script> import axios from "axios"; export default { name: "Product", components: {}, data() { return { categoryID: null, category: {}, // 单个分类为对象类型,初始值改空对象更合理 products: [], show: null }; }, computed: { // 过滤得到当前分类下的产品 currentCategoryProducts() { if (!this.category._id || !this.products.length) return []; return this.products.filter(product => product.category._id === this.category._id) } }, mounted() { axios .get(`http://localhost:5000/api/categories/${this.$route.params.id}`) .then(response => { this.category = response.data.category; }) .catch(error => { console.log(error); }); axios .get(`http://localhost:5000/api/products`) .then(response => { // 修正赋值,对应接口返回的products字段 this.products = response.data.products; }) .catch(error => { console.log(error); }); }, }; </script>
2. 修改模板遍历逻辑
将原来错误的函数调用写法,改为遍历计算属性返回的筛选后产品列表:
<div> <p>{{category.type}}</p> <div v-for="product in currentCategoryProducts" :key="product._id" > {{product.title}} </div> </div>
性能优化方案
上述方案是拉取全量产品后在前端过滤,产品数据量大时会浪费带宽,推荐改为后端直接返回对应分类的产品:
- 修改后端产品列表接口,支持按分类ID筛选:
router.get(`/products`, async (req, res) => { try { const query = {} // 传入分类ID时追加筛选条件 if (req.query.categoryId) { query.category = req.query.categoryId } const products = await Product.find(query) res.json({ success: true, products }); } catch (err) { res.status(500).json({ success: false, message: err.message }); } });
- 前端请求产品时直接传入当前分类ID,不需要前端过滤:
// mounted中产品请求改为 axios .get(`http://localhost:5000/api/products`, { params: { categoryId: this.$route.params.id } }) .then(response => { this.products = response.data.products; })
修改后模板直接遍历products即可,无需额外计算属性。
内容的提问来源于stack exchange,提问作者jibzy
相关产品推荐
相关产品推荐

