React/Vue implements optimization suggestions for routing authentication, navigation guards and routing interception

React/Vue implements optimization suggestions for routing authentication, navigation guards and routing interception

This article introduces how to implement route authentication, navigation guards and route interception in React and Vue. Routing authentication refers to verifying whether a user has permission to access a specific routing page according to user permissions. The navigation guard is a hook function executed before the routing switch, which is used to control the routing jump. Route interception is the act of intercepting certain specific routes during route processing. This article will introduce related concepts and implementation methods in React and Vue, and show how to apply these concepts to implement route authentication, navigation guards and route interception through sample code.

1 Introduction

React and Vue are currently very popular front-end frameworks, and they are loved by developers for their efficient development methods and flexibility. With the popularity of single-page applications (SPA), front-end routing has also become an integral part. In order to control the user's access rights in the application, implement Route Authorization, use Navigation Guards and Route Interception to become a common requirement.

In this paper, we will discuss the methods and technologies of implementing route authentication, navigation guard and route interception in React and Vue frameworks, as well as their advantages and disadvantages and applicable scenarios. We will discuss the following aspects:

First, we will introduce the concept and significance of routing authentication, and why we need to implement this function in the front-end application. As front-end applications become increasingly complex, user access control becomes more and more important. Routing authentication can help us verify the permissions of users when they access different pages of the application, so as to ensure that only users with corresponding permissions can correctly access the corresponding pages.

Then, we'll look at navigation guards in React and Vue. A navigation guard is a function or block of code that is executed before the user navigates to a different page. We'll focus on the navigation guards provided by React Router in React and Vue Router in Vue, and discuss their usage and usage considerations.

Next, we'll explore the concept and use of route interception. Route interception is a mechanism to intercept and process users before they visit a specific page. We'll discuss how route interception is implemented in React and Vue, and compare their similarities and differences. We will also discuss how to choose an appropriate routing interception solution based on business needs.

Finally, we will summarize and evaluate the methods and techniques for implementing routes, navigation guards, and route interception in React and Vue frameworks. We will compare their advantages and disadvantages, performance and applicable scenarios, and give some suggestions and best practices.

Through the research of this paper, we will provide developers with detailed guidance and suggestions on implementing route authentication, navigation guards and route interception in React and Vue. This will help developers provide a feasible and effective method when building front-end applications with strong security and complete permission control.

2 Route Authentication

2.1 Routing authentication in React

Implementing routing authentication in React can be done through the React Router library. The following is a basic routing authentication implementation example:

  1. First, install the React Router library:
npm install react-router-dom
  1. Set routing rules in the top-level component of the application, and add authentication logic for routes that require authentication. Suppose we have two routes that require authentication: /dashboardand /profile.
import {
    
     BrowserRouter as Router, Route, Redirect } from 'react-router-dom';

function App() {
    
    
  // 假设这里有一个表示用户登录状态的变量
  const isAuthenticated = true;

  return (
    <Router>
      <Route path="/" exact>
        <Redirect to="/dashboard" />
      </Route>
      <Route path="/dashboard" component={
    
    Dashboard} />
      <Route
        path="/profile"
        render={
    
    () =>
          isAuthenticated ? <Profile /> : <Redirect to="/" />
        }
      />
    </Router>
  );
}

In the above example, we used <Route>components to define routing rules. For routes that require authentication /profile, we use renderattributes to conditionally render <Profile />components or redirect to the homepage.

  1. If the user is not logged in, redirect to the login page. <Redirect>The redirection path can be set in the component .
<Route
  path="/profile"
  render={
    
    () =>
    isAuthenticated ? <Profile /> : <Redirect to="/login" />
  }
/>

In the example above, if the user is not logged in, it redirects to /loginthe page.

This is just a simple example, and you can perform more complex processing of route authentication according to actual needs. By using the components and APIs provided by React Router, you can implement flexible routing authentication mechanisms in React applications.

2.2 Routing authentication in Vue

In Vue, you can use Vue Router to implement routing authentication. Vue Router provides some options for Navigation Guards to validate before routing switches. By defining global navigation guards and local navigation guards, we can implement the routing authentication function.

The following is a basic routing authentication implementation example:

  1. First, install the Vue Router library:
npm install vue-router
  1. Set routing rules and navigation guards in Vue applications. Suppose we have two routes that require authentication: /dashboardand /profile.
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/',
      redirect: '/dashboard',
    },
    {
    
    
      path: '/dashboard',
      component: Dashboard,
    },
    {
    
    
      path: '/profile',
      component: Profile,
      meta: {
    
     requiresAuth: true },
    },
  ],
});

// 添加导航守卫
router.beforeEach((to, from, next) => {
    
    
  const isAuthenticated = true; // 假设这里有一个表示用户登录状态的变量

  // 如果路由需要鉴权
  if (to.meta.requiresAuth) {
    
    
    // 如果用户已登录,继续导航
    if (isAuthenticated) {
    
    
      next();
    } else {
    
    
      // 用户未登录,重定向到登录页面
      next('/');
    }
  } else {
    
    
    // 路由不需要鉴权,直接导航
    next();
  }
});

export default router;

In the above example, we first introduce Vue Router and initialize a routing instance. In routing rules, for routes that require authentication /profile, we use metafields to specify that authentication is required. Then, we beforeEachcheck the user's login status and the authentication requirements of the route through the navigation guard. If the user is not logged in and the route requires authentication, navigate to the login page, otherwise continue navigating to the target page.

  1. In Vue components, routes can be used directly to jump to routes that require authentication.
// 在某个 Vue 组件中使用
methods: {
    
    
  goToProfile() {
    
    
    this.$router.push('/profile');
  },
},

The above example is just a simple route authentication implementation, you can perform more complex processing according to actual needs. By using the navigation guard function provided by Vue Router, you can easily implement routing authentication in Vue applications.

3 Navigation Guards

3.1 Navigation guards in React

In React, navigation guards can be implemented using Higher-Order Components. By defining a wrapper component, we can perform some actions before or after the route switch, such as verifying the user login status, redirecting the page, etc.

React Router is the most commonly used routing library in React, which provides a <Route>way called components to define and render routes. Navigation guards can <Route>be implemented in components using the following methods:

  1. Use <Route>component renderproperties: You can specify a function to render the component, and judge the routing navigation guard logic in the function. For example:
<Route path="/dashboard" render={
    
    () => {
    
    
  if (loggedIn) {
    
    
    return <Dashboard />;
  } else {
    
    
    return <Redirect to="/login" />;
  }
}} />

In the above example, if the user is already logged in, <Dashboard>the component will be rendered, otherwise it will redirect to the login page.

  1. Use <Route>component componentproperties: You can directly specify a component to render, and execute the navigation guard logic through React's lifecycle hook function inside the component. For example:
class PrivateRoute extends React.Component {
    
    
  componentDidMount() {
    
    
    if (!loggedIn) {
    
    
      window.location.href = '/login';
    }
  }

  render() {
    
    
    return <Route {
    
    ...this.props} />;
  }
}

<PrivateRoute path="/dashboard" component={
    
    Dashboard} />

In the above example, PrivateRoutethe component will check if the user is logged in at mount time, and if not, it will redirect to the login page.

  1. Use a custom higher-order component (Higher-Order Component): You can create a higher-order component to encapsulate the routing component and execute the navigation guard logic inside the higher-order component.
const requireAuth = (Component) => {
    
    
  return class extends React.Component {
    
    
    componentDidMount() {
    
    
      if (!loggedIn) {
    
    
        window.location.href = '/login';
      }
    }

    render() {
    
    
      return <Component {
    
    ...this.props} />;
    }
  };
};

const ProtectedRoute = requireAuth(Dashboard);

<Route path="/dashboard" component={
    
    ProtectedRoute} />

In the example above, requireAutha function is a higher-order component that takes a component as an argument and returns a new component. The new component checks to see if the user is logged in, and if not, redirects to the login page.

These are some common ways to implement navigation guards in React, and the specific implementation method can be determined according to project requirements and personal preferences.

3.2 Navigation guards in Vue

In Vue, navigation guards are a mechanism for controlling routing jumps. It allows you to perform some specific logic before and after routing jumps.

Vue provides three navigation guards:

  1. Global pre-guard (beforeEach): Executed before routing jumps, can be used for permission verification, operations before page loading, etc.
  2. Global resolution guard (beforeResolve): Executed after the routing component is resolved and before rendering.
  3. Global post-hook (afterEach): Executed after the route jumps, it can be used for logging, operations after page jumps, etc.

In addition, you can also use route-exclusive guards in route configuration, such as:

  1. Route-exclusive pre-guard (beforeEnter): only takes effect for a specific route.
  2. Guards inside the component (beforeRouteEnter, beforeRouteUpdate, beforeRouteLeave): used inside the routing component to access the component instance.

The navigation guard is used as follows:

const router = new VueRouter({
    
    
  routes: [
    {
    
    
      path: '/home',
      component: Home,
      beforeEnter: (to, from, next) => {
    
    
        // 在路由独享的前置守卫中进行操作
        if (to.meta.requiresAuth && !auth.isLoggedIn()) {
    
    
          next('/login');
        } else {
    
    
          next();
        }
      }
    }
  ]
});

router.beforeEach((to, from, next) => {
    
    
  // 在全局前置守卫中进行操作
  if (to.meta.requiresAuth && !auth.isLoggedIn()) {
    
    
    next('/login');
  } else {
    
    
    next();
  }
});

router.afterEach((to, from) => {
    
    
  // 在全局后置钩子中进行操作
});

In the above code example, beforeEnterthe pre-guard exclusive to the route is used in the routing configuration, which beforeEachis the global pre-guard and afterEachthe global post-hook.

It should be noted that nextthe behavior of routing jumps can be controlled through functions in the guard. Calling next()means release, and calling next('/path')means jumping to the specified path.

4 Route interception

4.1 Route interception in React

In React, various libraries can be used to realize the function of route interception (Route Interception). Below is an example of route interception using the React Router library.

First, install the React Router library:

npm install react-router-dom

Then, use BrowserRouterthe component to wrap the entire application, and configure the routes that need to be intercepted:

import React from 'react';
import {
    
     BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom';

const App = () => {
    
    
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={
    
    Home} />
        <PrivateRoute path="/dashboard" component={
    
    Dashboard} />
        <Route path="/login" component={
    
    Login} />
        <Route component={
    
    NotFound} />
      </Switch>
    </Router>
  );
};

export default App;

In the above example, PrivateRouteit is a custom component used to intercept routes that require login to access. Here is PrivateRoutethe implementation of the component:

import React from 'react';
import {
    
     Route, Redirect } from 'react-router-dom';

const PrivateRoute = ({
     
      component: Component, ...rest }) => {
    
    
  const isAuthenticated = // 判断用户是否登录的逻辑

  return (
    <Route
      {
    
    ...rest}
      render={
    
    props => (
        isAuthenticated ? <Component {
    
    ...props} /> : <Redirect to="/login" />
      )}
    />
  );
};

export default PrivateRoute;

In the example above, PrivateRoutethe component receives a componentproperty that represents the component that needs to be intercepted. In renderthe method, by judging whether the user has logged in, if logged in, render the incoming component, otherwise redirect to the login page.

The above is an example of using the React Router library for route interception in React. According to specific needs, it can be customized and expanded according to the actual situation.

4.2 Route interception in Vue

In Vue, you can use route interceptors to intercept navigation to a route. Vue provides four routing interception methods: global pre-guard, global parsing guard, global post-hook and route exclusive guard.

  1. Global pre-guard (beforeEach): It is called before the route jumps, and can be used for permission verification and other operations.

    router.beforeEach((to, from, next) => {
          
          
      // 权限验证逻辑
      if (to.meta.auth && !isAuthenticated()) {
          
          
        next('/login');
      } else {
          
          
        next();
      }
    });
    
  2. Global resolution guard (beforeResolve): Called before routing jumps, used for data preparation and other operations of asynchronous routing.

    router.beforeResolve((to, from, next) => {
          
          
      // 异步数据准备逻辑
      fetchData().then(() => {
          
          
        next();
      });
    });
    
  3. Global post-hook (afterEach): It is called after the route jumps, and can be used for burying and other operations.

    router.afterEach((to, from) => {
          
          
      // 埋点逻辑
      trackPageView(to.path);
    });
    
  4. Route Exclusive Guard: The beforeEnter function specified when defining a route is used to independently intercept a route.

    const router = new VueRouter({
          
          
      routes: [
        {
          
          
          path: '/dashboard',
          component: Dashboard,
          beforeEnter: (to, from, next) => {
          
          
            // 自定义拦截逻辑
            if (!isAuthenticated()) {
          
          
              next('/login');
            } else {
          
          
              next();
            }
          }
        }
      ]
    });
    

In the above interceptor, the next function is used to control the routing jump behavior. Calling next() means normal jump, calling next(false) means interrupt jump, calling next('/login') means jumping to the specified path.

5 Example analysis

In this section, we will take an online shopping mall website as an example to demonstrate how to use React and Vue frameworks to realize the functions of route authentication, navigation guard and route interception. We will use two frameworks, React Router and Vue Router, to accomplish these functions, and provide some sample code to illustrate their usage and implementation details.

Route authentication, navigation guards, and route interception are very important when it comes to online shopping mall websites, because you may need to ensure that only authorized users can access certain pages, or execute certain logic before users access certain pages. Here is sample code to implement these features using React Router and Vue Router:

Use React Router to implement routing authentication and navigation guards:

import React from 'react';
import {
    
     BrowserRouter as Router, Route, Redirect } from 'react-router-dom';

// 鉴权逻辑
const isAuthenticated = true;

// 私有路由组件
const PrivateRoute = ({
     
      component: Component, ...rest }) => (
  <Route {
    
    ...rest} render={
    
    (props) => (
    isAuthenticated ? <Component {
    
    ...props} /> : <Redirect to="/login" />
  )} />
);

// 路由组件
const Home = () => <h1>Home</h1>;
const Dashboard = () => <h1>Dashboard</h1>;
const Profile = () => <h1>Profile</h1>;
const LoginPage = () => <h1>Login Page</h1>;

function App() {
    
    
  return (
    <Router>
      <Route path="/" exact component={
    
    Home} />
      <Route path="/login" component={
    
    LoginPage} />
      <PrivateRoute path="/dashboard" component={
    
    Dashboard} />
      <PrivateRoute path="/profile" component={
    
    Profile} />
    </Router>
  );
}

export default App;

Use Vue Router to implement routing authentication and navigation guards:

import Vue from 'vue';
import VueRouter from 'vue-router';

// 鉴权逻辑
const isAuthenticated = true;

// Vue Router 安装
Vue.use(VueRouter);

// 导航守卫
const router = new VueRouter({
    
    
  routes: [
    {
    
     path: '/', component: Home },
    {
    
     path: '/login', component: LoginPage },
    {
    
    
      path: '/dashboard',
      component: Dashboard,
      meta: {
    
     requiresAuth: true },
    },
    {
    
    
      path: '/profile',
      component: Profile,
      meta: {
    
     requiresAuth: true },
    },
  ],
});

router.beforeEach((to, from, next) => {
    
    
  if (to.meta.requiresAuth) {
    
    
    if (isAuthenticated) {
    
    
      next();
    } else {
    
    
      next('/login');
    }
  } else {
    
    
    next();
  }
});

// Vue 实例
new Vue({
    
    
  router,
  render: (h) => h(App),
}).$mount('#app');

The above example demonstrates how to use React Router and Vue Router to implement routing authentication and navigation guards. In both examples, we decide whether to navigate to a particular route by checking if we are authenticated. If not authenticated or not logged in, it will redirect to the login page.

This is just a simple example, you can perform more complex processing on route authentication, navigation guard and route interception according to actual needs. React Router and Vue Router provide more features and options, enabling you to customize and control routing behavior according to your needs.

6 Conclusion

This article introduces how to implement route authentication, navigation guards and route interception in React and Vue. Through the functions provided by React Router and Vue Router, we can easily manage and control the routing authority and jump logic of the front-end application. Whether using React or Vue, developers can choose the appropriate method to implement routing management according to their needs and business scenarios. These functions can not only improve the security and user experience of front-end applications, but also improve development efficiency and code maintainability.

Both React and Vue can implement route authentication, navigation guards, and route interception. Here is a conclusion:

  1. Route authentication in React can be implemented using the React Router library. React Router provides a <Route>component on which routes that require authentication can be set. <Route>A property can be set on the component renderto determine whether the current user has permission to access the route. For example:
<Route path="/protected" render={
    
    () => (
  isLoggedIn ? (<ProtectedComponent />) : (<Redirect to="/login" />)
)} />
  1. Routing authentication in Vue can be implemented using the Vue Router library. Vue Router provides a beforeEachmethod in which the authentication logic of the route can be set. For example:
router.beforeEach((to, from, next) => {
    
    
  if (to.meta.requiresAuth && !isLoggedIn) {
    
    
    next('/login');
  } else {
    
    
    next();
  }
});
  1. Navigation guards are some hook functions triggered before and after route jumps, which can be used to handle specific route jump situations. Both React Router and Vue Router provide similar navigation guards. For example, React Router provides onEnterand onLeavehook functions, which can handle the logic before and after the route jump in these hook functions. Vue Router provides beforeEach, beforeResolve, afterEachand other hook functions, which can handle the logic before and after the routing jump in these hook functions.

  2. Route interception refers to preventing or modifying the default jump behavior when routing jumps. nextIn React and Vue, route interception can be achieved by using methods in navigation guards . For example, it can be called in the navigation guard next(false)to prevent route jump, or call next('/someOtherPath')to modify the default jump path.

Both React and Vue provide corresponding libraries and methods to implement route authentication, navigation guards and route interception. The approach can vary depending on the specific needs and project framework.

Guess you like

Origin blog.csdn.net/weixin_55756734/article/details/131710404