Home > Web Front-end > Front-end Q&A > How to use vue guard

How to use vue guard

PHPz
Release: 2023-04-26 14:52:48
Original
571 people have browsed it

Vue is a popular JavaScript framework that provides many features and options to help developers create responsive web applications. Guard is a very important concept in Vue. This article will discuss the basic uses and cases of Vue guards.

Vue Guard Overview

In Vue, a guard is a function that can listen to the life cycle events of routes and components. When these events are triggered, guards can perform actions such as verifying user permissions, copying and inspecting incoming data, etc. Vue guards are divided into two categories: global guards and routing guards. The main difference between them lies in the objects they monitor.

Global guard

Global guard is associated with the life cycle of the Vue application. They can perform some operations when each Vue instance is created, destroyed, updated or mounted. Global guards include the following four hook functions:

  1. beforeCreate: called after the Vue instance is initialized, but before data observation and event/watcher event configuration. This hook function is a good time to initialize component-level data/state.
  2. created: Called after the Vue instance is created. At this time, the component instance is not mounted in the DOM. You can perform some asynchronous operations in this hook function, but it is not recommended to modify the component's state data in it.
  3. beforeMount: Called before the Vue instance is mounted into the DOM element. At this time, the component's template has been compiled into an HTML string, but has not yet been inserted into the DOM.
  4. mounted: Called after the Vue instance is mounted on the DOM element. You can access DOM elements and perform other operations inside this hook function, such as initializing third-party plug-ins, etc.

Route Guard

Route guard is a hook function that is triggered when the application navigates to a specific route. They can monitor the access history of routes, check whether users have permission to access specific routes, handle asynchronous data loading, and other operations. Vue's route guard includes the following six hook functions:

  1. beforeRouteEnter: called before the route enters the component. The component instance can be accessed in this hook function, but the state data and instance methods within the component cannot be accessed.
  2. beforeRouteUpdate: Called when the route is updated. Generally used to handle operations such as asynchronous data loading.
  3. beforeRouteLeave: Called when the route leaves the component. You can use guards to validate user input or alert users about unsaved changes.
  4. beforeEach: Called before navigating to a new route. You can check user permissions, handle asynchronous data loading and other operations in this hook function.
  5. afterEach: Called after navigation is completed. Errors that occur during navigation can be handled in this hook function.
  6. onError: Called when there is an error in route navigation. Exceptions such as request failure and network errors can be handled in this hook function.

Using Vue guards

Vue guards are very important in actual development. They can be used to handle business logic in various scenarios. Below we use an example to demonstrate the basic use of Vue guards.

Suppose there is a page that requires the user to log in to access. When the user is not logged in, he needs to be redirected to the login page. We can use the beforeEach guard to achieve this functionality. First define a routing array:

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/profile',
    name: 'profile',
    component: Profile,
    meta: {
      requiresAuth: true
    }
  }
]
Copy after login

In the routing configuration, we specify the /profile route that requires login to access, and mark it as requiring authentication through routing meta information. Next, add the beforeEach hook function in the router.js file:

router.beforeEach((to, from, next) => {
  const currentUser = firebase.auth().currentUser;
  const requiresAuth = to.matched.some(record => record.meta.requiresAuth);
  if (requiresAuth && !currentUser) {
    next('/login');   //如果需要登录并且用户未登录,则重定向到登录页面
  } else {
    next();   //否则允许导航到目标路由
  }
});
Copy after login

In the beforeEach hook function, we first get the current user object currentUser, and then use the requiresAuth attribute to determine whether the target route requires login to access. If login is required and the current user is not logged in, redirect to the login page. Otherwise, allow navigation to the target route (using the next() method to allow navigation).

Conclusion

Vue guard is a very important concept in the Vue framework. It can be used to monitor the life cycle events of routing and components, and perform some operations when these events are triggered, such as authenticating users. Permissions, copying and inspecting incoming data, etc. This article introduces the basic knowledge of global guards and routing guards, and provides an example to demonstrate the basic use of Vue guards. It is designed to allow developers to better understand and use Vue guards, and to fully utilize their role in actual development.

The above is the detailed content of How to use vue guard. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template