React/Vue implements routing authentication/navigation guard/routing interception

Vue /React implements routing authentication/navigation guard/routing interception (react-router v6)

1. React  project

1. Implementation ideas

Encapsulate  AuthRoute high-level components of routing authentication by yourself, realize non-login interception, and jump to the login page

The idea is: judge whether there is a token locally, if so, return the subcomponent, otherwise redirect to Login

2. Implementation steps

  1. In the components directory, create the AuthRoute/index.js file

  2. Determine whether to log in

  3. When logging in, directly render the corresponding page component

  4. Redirect to login page when not logged in

  5. Replace the page routing configuration that requires authentication with the AuthRoute component rendering

3. Code implementation

/src/routes/AuthRoute.js

// 路由鉴权
// 1. 判断token是否存在
// 2. 如果存在 直接正常渲染
// 3. 如果不存在 重定向到登录路由

import { Navigate } from "react-router-dom";
// 高阶组件:把一个组件当成另外一个组件的参数传入 然后通过一定的判断 返回新的组件
// 这里的AuthRoute就是一个高阶组件

function AuthRoute({ children }) {
  // 获取token
  const tokenStr = window.localStorage.getItem('token');
  // 如果token存在 直接正常渲染
  if (tokenStr) {
    return <>{children}</>
  }
  // 如果token不存在,重定向到登录路由
  else {
    return <Navigate to='/login' replace />
  }
}
{/*
 <AuthRoute> <Layout /> </AuthRoute> 
 登录:<> <Layout /> </>
 非登录:<Navigate to="/login" replace />
*/ }
function LoginRoute({ children }) {
  const token = window.localStorage.getItem('token');
  if (token) {
    return <Navigate to="/" replace></Navigate>;
  } else {
    return <>{children}</>;
  }
}
export { AuthRoute,LoginRoute }

src/routes/index.js routing table file

import Layout from "@/pages/Layout";
import Login from "@/pages/Login";
import { AuthRoute ,LoginRoute} from "@/routes/AuthRoute";

// eslint-disable-next-line
export default [
  // 不需要鉴权的组件Login
  {
    path: "/login",
    element: <LoginRoute>
                <Login />
             </LoginRoute>
  },
  // 需要鉴权的组件Layout
  {
    path: "/",
    element: <AuthRoute>
      <Layout />
    </AuthRoute>
  }
]

2.  In the Vue project

1. Implementation ideas

In Vue's router routing table file, there is an official packaged API: beforeEach.

2. Code implementation

/src/router/index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由懒加载
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Home.vue')
const Welcome = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Welcome.vue')
Vue.use(VueRouter)
const routes = [
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      { path: "/welcome", component: Welcome }
    ]
  }
]
const router = new VueRouter({
  routes
})
// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to代表将要访问的路径
  // from代表从哪个路径跳转而来
  // next是一个函数,表示放行
  //    next() 放行   next('/login') 强制跳转到login页面
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router

3. Code explanation:

  • router.beforeEach is used to set Vue's route navigation guard (route interception), which receives a callback function as a parameter.

  • Inside the callback function, three parameters are received in order: to, from, next.

  • to represents the path to be accessed

  • from represents which path to jump from

  • next is a function that means release

  • next() => release, next('/login') => forced to jump to the login page

Guess you like

Origin blog.csdn.net/sinat_36728518/article/details/131682951