Cli*_*ote 10 javascript vue.js vue-router
I have the following sequence happening:
Main screen
Loading screen
Results screen
在主页上,当有人单击按钮时,我将其通过以下方式发送到加载屏幕:
this.$router.push({path: "/loading"});
任务完成后,将通过以下方式将其发送到结果屏幕
this.$router.push({path: "/results/xxxx"});
问题是,通常他们希望从结果返回主屏幕,但是当他们单击返回时,它们将被发送到再次加载,从而将它们发送回结果,因此它们陷入了无限循环并且无法前进返回主屏幕。
任何想法如何解决这一问题?理想情况下,我希望有一个类似的选择:
this.$router.push({path: "/loading", addToHistory: false});
这会将他们发送到该路线而不将其添加到历史记录中。
nbw*_*ard 22
这应该有一个真正的答案this.$router.replace:
// On login page
// Use 'push' to go to the loading page.
// This will add the login page to the history stack.
this.$router.push({path: "/loading"});
// Wait for tasks to finish
// Use 'replace' to go to the results page.
// This will not add '/loading' to the history stack.
this.$router.replace({path: "/results/xxxx"});
Run Code Online (Sandbox Code Playgroud)
为了进一步阅读,Vue Router在幕后使用History.pushState()和History.replaceState() 。
有一种完美的方法来处理这种情况
您可以使用组件内防护来控制颗粒级别的路线
在代码中进行以下更改
在主屏幕组件中
在组件选项中添加此beofreRouteLeave防护,在转到“结果屏幕”之前,您将路线设置为仅通过加载屏幕
beforeRouteLeave(to, from, next) {
if (to.path == "/result") {
next('/loading')
}
next();
},
Run Code Online (Sandbox Code Playgroud)
正在加载屏幕组件
如果路线从结果返回到加载,则它不应降落在此处并直接跳转到主屏幕
beforeRouteEnter(to, from, next) {
if (from.path == "/result") {
next('/main')
}
next();
},
Run Code Online (Sandbox Code Playgroud)
在加载屏幕中,beforeRouteEnter防护措施对此无权访问,因为在确认导航之前调用了该防护措施,因此甚至尚未创建新的输入组件。因此,利用此优势,从结果屏幕进行路由时,您将不会触发无限呼叫
结果屏幕组件
如果您使用返回,则它不应降落在加载中,而直接跳转到主屏幕
beforeRouteLeave(to, from, next) {
if (to.path == "/loading") {
next('/')
}
next();
},
Run Code Online (Sandbox Code Playgroud)
我刚刚创建了一个小型Vue应用程序来重现相同的问题。根据您的问题,它在我的本地计算机上有效。希望它也能解决您的问题。