Vue.js中如何正确获取指定title的产品详情?
问题解决:Vue路由参数与接口请求参数不匹配导致无法获取产品详情
问题核心
你的路由配置以title作为动态参数(/products/:title),但在axios请求时错误使用了不存在的this.$route.params.id作为请求参数,导致请求地址无效,无法获取产品数据。当前路由参数中仅存在title(值为tecno),id字段未定义。
解决方案(根据后端接口支持情况二选一)
方案一:后端接口支持通过产品title查询
直接将请求中的this.$route.params.id替换为this.$route.params.title,匹配当前路由传递的参数。修改后的组件脚本如下:
<script> import axios from "axios"; export default { name: "Product", components: {}, data() { return { product: [] }; }, mounted() { console.log("the title is :" + this.$route.params.title); axios .get(`http://localhost:5000/api/products/${this.$route.params.title}`, {}) .then(response => { console.log(response); this.product = response.data.product; }) .catch(error => { console.log(error); }); }, }; </script>
方案二:后端接口仅支持通过_id查询
如果后端只能通过产品的_id字段查询,需要调整路由参数和跳转逻辑:
- 修改路由配置:将动态参数从
title改为id
// 路由配置文件 { path: "/products/:id", name: "Product", component: Product }
- 修改路由跳转的
router-link:传递产品的_id而非title
<!-- 示例:列表页的router-link --> <router-link :to="{ name: 'Product', params: { id: product._id } }"> {{ product.title }} </router-link>
- 组件中保持使用
this.$route.params.id请求(同时修正控制台日志):
<script> import axios from "axios"; export default { name: "Product", components: {}, data() { return { product: [] }; }, mounted() { console.log("the id is :" + this.$route.params.id); axios .get(`http://localhost:5000/api/products/${this.$route.params.id}`, {}) .then(response => { console.log(response); this.product = response.data.product; }) .catch(error => { console.log(error); }); }, }; </script>
内容的提问来源于stack exchange,提问作者chunfee
相关产品推荐
相关产品推荐

