在 Vue.js 中,如何防止子路由导航? [英] In Vue.js, how do you prevent navigation for a subroute?
问题描述
beforeRouteLeave
的好处是你可以防止在某些情况下导航离开.
The nice thing about beforeRouteLeave
is that you can prevent navigating away under certain conditions.
我有一个设置,它使用子路由来呈现页面的一部分.我想要一个子路由上的导航守卫,以防止在未保存数据的情况下切换到另一个.
I have a setup that uses a subroute to render part of the page. I would like a navigation guard on the subroute to prevent switching to another one if the data is not saved.
{
path: '/customers/view',
component: ViewCustomerShell,
children: [
{path: ':id', name: 'ViewCustomer', component: ViewCustomer}
]
},
所以当我访问 /customers/view/12
并进行更改时,如果他们尝试加载 /customers/view/13
,我想弹出通常的确认并可能停止导航.由于在这种情况下不会调用 beforeRouteLeave
,那么推荐的防止导航的方法是什么?看$route
好像来不及了,因为那时导航已经发生了.
So when I visit /customers/view/12
and make a change, if they try to load /customers/view/13
, I want to pop up the usual confirmation and potentially stop navigation. Since beforeRouteLeave
is not called in this situation, what is the recommended approach for preventing navigation? It seems that watching $route
would be too late, because then the navigation has already occurred.
注意:如上所述,在这种情况下不会调用beforeRouteLeave
;它不起作用.
Note: As mentioned above, beforeRouteLeave
is not called in this situation; it doesn't work.
注意:使用 onbeforeunload
不起作用,因为它仅在整个页面更改时触发.
Note: Using onbeforeunload
doesn't work because it only triggers when the entire page changes.
推荐答案
我知道这个帖子很老了.但这是我在寻找相同问题时发现的第一个.我不知道现在是否有更好的解决方案,但对于那些正在寻找解决方案的人,我可以分享我的:
I know that this post is very old. but it was the first one I found when looking for the same problem. I have no idea if there is a better solution nowadays but for those who are looking for a solution, I can share mine:
1.定义全局状态
let isRouteChangeBlocked: boolean = false;
export function blockRouteChange(set?: boolean): boolean {
if (arguments.length == 1) {
isRouteChangeBlocked = !!set;
return isRouteChangeBlocked;
}
return isRouteChangeBlocked;
}
2.替换路由功能
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function(location: RawLocation) {
if (blockRouteChange()) {
if (confirm("Du hast ungespeicherte Änderungen, möchtest du fortfahren?")) {
blockRouteChange(false);
return originalPush.call(this, location) as any;
}
return;
}
return originalPush.call(this, location) as any;
};
3.设置状态
@Watch("note.text")
private noteTextChanged() {
blockRouteChange(true);
}
这正是我想要的.如果现在有更好的解决方案,请告诉我.你可以在这里获得完整的可运行示例:https://github.com/gabbersepp/dev.to-posts/tree/master/blog-posts/vuejs-avoid-routes/code/example
This does exactly what I want. If nowadays there is a better solution, let me know. You can get the full runnable example here: https://github.com/gabbersepp/dev.to-posts/tree/master/blog-posts/vuejs-avoid-routes/code/example
这篇关于在 Vue.js 中,如何防止子路由导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!