Vue.js中mounted函数多次触发导致axios接口返回404问题如何解决
可行解决方案如下:
根因说明
报错是因为二次进入页面时this.$route.params.id未获取到有效值,导致请求路径拼接了undefined触发404错误,可按以下优先级修复:
- 方案1:新增参数合法性校验,拦截无效请求
先对拿到的路由参数做非空判断,避免无意义的接口请求,同时增加兜底逻辑:
async mounted(){ const header = { 'Authorization': 'Bearer ' + this.LoginUserData, }; this.editId = this.$route.params.id; // 新增参数校验 if (!this.editId) { // 示例兜底逻辑:跳回账单列表页,可根据业务调整 this.$message.error('账单ID不存在,跳转回列表') this.$router.push('/bill/list') return } try{ console.log(this.editId); let response = await axios.get(`/api/backend/bill/${this.editId}` ,{headers: header}); this.form = response.data; }catch(err){ // 建议补充错误提示逻辑 console.error('账单详情获取失败', err) } },
- 方案2:修正路由传参逻辑,避免参数丢失
params传参丢失绝大多数是路由配置或跳转方式不规范导致:
- 首先确认路由配置中已经声明了动态参数:
// 路由配置示例 { path: '/bill/edit/:id', // 必须声明:id占位符 name: 'BillEdit', component: () => import('@/views/bill/Edit.vue') }
- 跳转时不要混用path和params传参,二选一即可:
// 方式1:用name+params传参 this.$router.push({ name: 'BillEdit', params: { id: 你的账单ID } }) // 方式2:直接把参数拼在path里 this.$router.push(`/bill/edit/${你的账单ID}`)
- 方案3:兼容组件缓存/参数变化场景
如果你的项目开启了<keep-alive>缓存页面组件,mounted只会在首次加载时触发一次,后续进入组件不会重新执行,此时可以把请求逻辑抽离为公共方法,同时监听路由参数变化:
export default { components: { Datepicker,datetime }, data() { return { editId: null, form: {} } }, async mounted(){ // 组件首次加载触发 this.getBillDetail() }, watch: { // 路由参数变化时重新触发请求 '$route.params.id': { immediate: true, handler() { this.getBillDetail() } } }, methods: { async getBillDetail() { const header = { 'Authorization': 'Bearer ' + this.LoginUserData, }; this.editId = this.$route.params.id; if (!this.editId) { this.$message.error('账单ID不存在,跳转回列表') this.$router.push('/bill/list') return } try{ let response = await axios.get(`/api/backend/bill/${this.editId}` ,{headers: header}); this.form = response.data; }catch(err){ console.error('账单详情获取失败', err) } } } }
内容的提问来源于stack exchange,提问作者user3653474
相关产品推荐
相关产品推荐

