Vue3编辑页判断Vuex store无对应任务时跳转404,created不生效如何解决
问题根因
你遇到的跳转不生效是两个原因共同导致的:
- Vue组件的生命周期钩子是顺序同步执行的,
created中触发的$router.push是异步操作,不会立刻中断后续mounted钩子的执行 - 当store中无匹配任务时,
mounted中直接访问task.desc会抛出JS运行错误,阻塞后续路由跳转逻辑的执行
解决方案
快速修复现有代码
在mounted中新增task存在性判断,避免空值访问报错:
<script> export default { name: "EditTaskForm", data() { return { newTaskDesc: "", }; }, created() { const task = this.$store.getters.getTaskById(Number(this.$route.params.id)); if (!task) { this.$router.push("/404"); // 提前终止后续逻辑执行 return } }, mounted() { const task = this.$store.getters.getTaskById(Number(this.$route.params.id)); // 新增判断,task存在才赋值 if (task) { this.newTaskDesc = task.desc; } }, methods: { submitEdit() { this.$store.dispatch("editTask", { newTaskDesc: this.newTaskDesc, id: Number(this.$route.params.id), }); this.$router.push("/"); }, }, }; </script>
更规范的优化方案
建议将存在性校验逻辑放到路由全局前置守卫或者路由独享守卫中,在进入编辑页之前就完成校验,不存在匹配任务时直接跳404,避免加载编辑组件后再跳转的体验问题,参考实现:
// router/index.js 路由配置文件中添加独享守卫 const routes = [ // 其他路由配置 { path: '/edit/:id', component: EditTaskForm, beforeEnter: (to, from, next) => { const task = store.getters.getTaskById(Number(to.params.id)) if (!task) { next('/404') } else { next() } } } ]
这样修改后,组件内部不需要再做存在性判断,mounted中可以直接访问task.desc。
内容的提问来源于stack exchange,提问作者Martin Pilaszek
相关产品推荐
相关产品推荐

