What are the navigation guards of Vue?
Navigation guards include: 1. Global pre-guard "beforeEach"; 2. Global parsing guard "beforeResolve"; 3. Route-exclusive guard "beforeEnter"; 4. Guard within the component "beforeRouteEnter", "beforeRouteLeave".
The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.
The navigation guard provided by vue-router is mainly used to guard navigation by jumping or canceling. There are multiple opportunities to build into the route navigation process: globally, exclusive to a single route, or at the component level.
Remember that changes to parameters or queries will not trigger entry/leave navigation guards. You can respond to these changes by observing the $route object, or using the beforeRouteUpdate in-component guard.
Global front guard
You can use router.beforeEach to register a global front guard:
const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... })
When a navigation is triggered, the global front guard Set guards are called in the order they are created. Guards are parsed and executed asynchronously. At this time, the navigation is waiting until all guards are resolved.
Each guard method receives three parameters:
to: Route: The target routing object to be entered
from: Route: The route that the current navigation is about to leave
next: Function: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.
next(): Proceed to the next hook in the pipeline. If all hooks are executed, the navigation status is confirmed.
next(false): Interrupt current navigation. If the browser's URL changes (perhaps manually by the user or by the browser's back button), the URL address will be reset to the address corresponding to the from route.
next('/') or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new navigation is started. You can pass an arbitrary location object to next, and options such as replace: true, name: 'home', and any options used in router-link's to prop or router.push are allowed to be set.
next(error): (2.4.0) If the parameter passed to next is an Error instance, the navigation will be terminated and the error will be passed to router.onError() Registered callback.
# Ensure that the next function is called exactly once in any given navigation guard. It can appear more than once, but only if all logical paths do not overlap, otherwise the hook will never be parsed or an error will be reported. Here's an example of redirecting to /login when the user fails to authenticate:
// BAD router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' }) // 如果用户未能验证身份,则 `next` 会被调用两次 next() }) // GOOD router.beforeEach((to, from, next) => { if (to.name !== 'Login' && !isAuthenticated) next({ name: 'Login' }) else next() })
Global Resolution Guard
New in 2.5.0
In 2.5.0 you can use router.beforeResolve to register a global guard. This is similar to router.beforeEach , except that the parsing guard is called before the navigation is confirmed, and after all in-component guards and async routing components have been parsed.
Routing-exclusive guards
You can directly define beforeEnter guards in the routing configuration:
const router = new VueRouter({ routes: [ { path: '/foo', component: Foo, beforeEnter: (to, from, next) => { // ... } } ] })
The methods of these guards and global pre-guards The parameters are the same.
Guards within the component
Finally, you can define the following route navigation guards directly within the routing component:
beforeRouteEnter
beforeRouteUpdate (new in 2.2)
beforeRouteLeave
const Foo = { template: `...`, beforeRouteEnter(to, from, next) { // 在渲染该组件的对应路由被 confirm 前调用 // 不!能!获取组件实例 `this` // 因为当守卫执行前,组件实例还没被创建 }, beforeRouteUpdate(to, from, next) { // 在当前路由改变,但是该组件被复用时调用 // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候, // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。 // 可以访问组件实例 `this` }, beforeRouteLeave(to, from, next) { // 导航离开该组件的对应路由时调用 // 可以访问组件实例 `this` } }
beforeRouteEnter The guard cannot access this, Because the guard is called before the navigation is confirmed, the new component that is about to appear has not yet been created.
However, you can access the component instance by passing a callback to next. Execute the callback when the navigation is confirmed, and pass the component instance as the parameter of the callback method.
beforeRouteEnter (to, from, next) { next(vm => { // 通过 `vm` 访问组件实例 }) }
Note that beforeRouteEnter is the only guard that supports passing callbacks to next. For beforeRouteUpdate and beforeRouteLeave, this is already available, so passing callbacks is not supported because it is not necessary.
beforeRouteUpdate (to, from, next) { // just use `this` this.name = to.params.name next() }
This leave guard is usually used to prevent users from leaving suddenly before saving changes. This navigation can be canceled with next(false).
beforeRouteLeave (to, from, next) { const answer = window.confirm('Do you really want to leave? you have unsaved changes!') if (answer) { next() } else { next(false) } }
Complete navigation parsing process
Navigation is triggered.
Call the beforeRouteLeave guard in the deactivated component.
Call the global beforeEach guard.
Call the beforeRouteUpdate guard (2.2) in the reused component.
Call beforeEnter in routing configuration.
Resolve asynchronous routing components.
Call beforeRouteEnter in the activated component.
Call the global beforeResolve guard (2.5).
Navigation confirmed.
Call the global afterEach hook.
Trigger DOM update.
Call the callback function passed to next in the beforeRouteEnter guard, and the created component instance will be passed in as a parameter of the callback function.
[Related recommendations: "vue.js tutorial"]
The above is the detailed content of What are the navigation guards of Vue?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values for each element; and the .map method can convert array elements into new arrays.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.
