From: Stuart Jones Date: Fri, 18 Feb 2022 23:16:10 +0000 (+1030) Subject: docs: add redirect guard example (#1311) X-Git-Tag: v4.0.13~14 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4cb394902f412d16e065704e6a1172da3016634b;p=thirdparty%2Fvuejs%2Frouter.git docs: add redirect guard example (#1311) Co-authored-by: Eduardo San Martin Morote --- diff --git a/docs/guide/advanced/navigation-guards.md b/docs/guide/advanced/navigation-guards.md index 15c2dd3e..ec1ed61e 100644 --- a/docs/guide/advanced/navigation-guards.md +++ b/docs/guide/advanced/navigation-guards.md @@ -28,6 +28,19 @@ And can optionally return any of the following values: - `false`: cancel the current navigation. If the browser URL was changed (either manually by the user or via back button), it will be reset to that of the `from` route. - A [Route Location](../../api/#routelocationraw): Redirect to a different location by passing a route location as if you were calling [`router.push()`](../../api/#push), which allows you to pass options like `replace: true` or `name: 'home'`. The current navigation is dropped and a new one is created with the same `from`. + ```js + router.beforeEach(async (to, from) => { + if ( + // make sure the user is authenticated + !isAuthenticated && + // ❗️ Avoid an infinite redirect + to.name !== 'Login' + ) { + // redirect the user to the login page + return { name: 'Login' } + } + }) + It's also possible to throw an `Error` if an unexpected situation was met. This will also cancel the navigation and call any callback registered via [`router.onError()`](../../api/#onerror). If nothing, `undefined` or `true` is returned, **the navigation is validated**, and the next navigation guard is called.