Vue.js组件挂载后更新运费报错:无法读取price属性
Vue组件挂载修改运费时出现TypeError错误
相关代码与信息
模板代码
<div> <input type="radio" name="order" checked="checked" @change="onChooseShipping('normal')" /> Normal </div>
Mounted钩子请求代码
async mounted() { try { let response = await axios.post("http://localhost:5000/api/shipment", { shipment: normal }); console.log(response) this.$store.commit("setShipping", { price: response.shipment.price, estimatedDelivery: response.shipment.estimated }); this.price = response.shipment.price; this.estimatedDelivery = response.shipment.estimated; } catch (err) { console.log(err) } }
接口返回JSON数据
{ "success": true, "shipment": { "estimated": "Tuesday August 30th", "price": 13.98 } }
错误信息
TypeError: Cannot read properties of undefined (reading 'price') at VueComponent.mounted
解决步骤
- 修正Axios响应数据的访问路径
Axios会把接口返回的实际数据封装在响应对象的data属性中,直接访问response.shipment会得到undefined,进而导致读取price失败。需将所有response.shipment替换为response.data.shipment:
修改后的代码:
async mounted() { try { let response = await axios.post("http://localhost:5000/api/shipment", { shipment: normal }); console.log(response.data) // 打印实际返回的数据确认结构 this.$store.commit("setShipping", { price: response.data.shipment.price, estimatedDelivery: response.data.shipment.estimated }); this.price = response.data.shipment.price; this.estimatedDelivery = response.data.shipment.estimated; } catch (err) { console.log(err) } }
- 检查
normal变量是否定义
代码中shipment: normal里的normal如果是字符串类型,需要用引号包裹成shipment: 'normal',否则会因变量未定义抛出新的错误。
内容的提问来源于stack exchange,提问作者xander
相关产品推荐
相关产品推荐

