Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the beforeEach endless cycle in vue

Shulou Source: shulou.com Published: 2022-05-31 12:00:53 10月03日 Update

This article mainly introduces the relevant knowledge of "how to solve the beforeEach endless cycle in vue". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this article "how to solve the beforeEach endless cycle in vue" can help you solve the problem.

What is beforeEach?

BeforeEach is a vue-router routing navigation hook, which I usually use as a routing guard.

What is a routing guard?

Doing some verification before the route jump, such as login authentication, is a common requirement in websites. In this regard, the beforeRouteUpdate provided by vue-route can easily implement navigation guard (navigation-guards). The name navigation-guards sounds strange, but since the official document is translated in this way, let's call it that.

For example, when we don't log in, we jump to the login page. If logged in, it jumps normally.

Let's take a look at the endless loop code.

Export const router = new Router (RouterConfig); router.beforeEach ((to, from, next) = > {let token = sessionStorage.getItem ('token'); if (token) {next ();} else {next ({path:' / p404'})})

When token does not exist in session, jump to / p404, at this time the route changes, judge again, then jump to / 404, resulting in an endless loop. Make a judgment in the code, and if you jump to p404, let it route with peace of mind. The modified code is as follows.

Export const router = new Router (RouterConfig); router.beforeEach ((to, from, next) = > {let token = sessionStorage.getItem ('token'); if (token) {next ();} else {if (to.path = =' / p404') {next ();} else {next ({path:'/ p404'})}}) This is the end of the introduction to "how to solve the beforeEach endless cycle in vue". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Routing looping login knowledge navigation code industry authentication different practical example content again name descendant official practical practical this documentation Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Microsoft Linux Redmi Docker