]> git.ipfire.org Git - thirdparty/vuejs/router.git/commitdiff
docs: add redirect guard example (#1311)
authorStuart Jones <horuskol@users.noreply.github.com>
Fri, 18 Feb 2022 23:16:10 +0000 (09:46 +1030)
committerGitHub <noreply@github.com>
Fri, 18 Feb 2022 23:16:10 +0000 (00:16 +0100)
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com>
docs/guide/advanced/navigation-guards.md

index 15c2dd3e0c93306a384a75146ad2ea858a8f4913..ec1ed61e086b707199d4332aba28d6cecefc76ea 100644 (file)
@@ -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.