[JavaScript] 纯文本查看 复制代码
...
router.beforeEach(async(to, from, next) => {
const toPath = to.path;
const fromPath = from.path;
})
...
[JavaScript] 纯文本查看 复制代码
import * as React from 'react';
import { HashRouter,Switch,Route,Redirect } from 'react-router-dom';
import { HomePage } from '../pages/home/home.page';
import { LoginPage } from '../pages/login/login.page';
import { ErrorPage } from '../pages/error/error.page';
export const Router = () => (
<HashRouter>
<Switch>
<Route path="/" exact component={HomePage}/>
<Route path="/login" exact component={LoginPage}/>
<Route path="/home" exact component={HomePage}/>
<Route path="/404" exact component={ErrorPage}/>
<Redirect to="/404" />
</Switch>
</HashRouter>
);
[JavaScript] 纯文本查看 复制代码
import { HomePage } from '../pages/home/home.page';
import { LoginPage } from '../pages/login/login.page';
import { ErrorPage } from '../pages/error/error.page';
interface routerConfigModel {
path:string,
component?:any,
auth?:boolean
}
export const routerConfig:routerConfigModel[] = [
{
path:'/',
component:HomePage,
auth:true,
},{
path:'/home',
component:HomePage,
auth:true,
},{
path:'/login',
component:LoginPage,
},{
path:'/404',
component:ErrorPage
}
];
[JavaScript] 纯文本查看 复制代码
import * as React from 'react';
import { HashRouter,Switch } from 'react-router-dom';
import { FrontendAuth } from '../components/frontend-auth/frontend-auth.component'
import { routerConfig } from './router.config'
export class Router extends React.Component{
render(){
return(
<HashRouter>
<Switch>
<FrontendAuth config={routerConfig} />
</Switch>
</HashRouter>
);
}
}
[JavaScript] 纯文本查看 复制代码
import * as React from 'react';
import { Route,Redirect } from 'react-router-dom';
import { propsModel } from './frontend-auth.model'
export class FrontendAuth extends React.Component<any,propsModel>{
render(){
const { location,config } = this.props;
const { pathname } = location;
const isLogin = localStorage.getItem('__config_center_token')
// 如果该路由不用进行权限校验,登录状态下登陆页除外
// 因为登陆后,无法跳转到登陆页
// 这部分代码,是为了在非登陆状态下,访问不需要权限校验的路由
const targetRouterConfig = config.find((v:any) => v.path === pathname);
if(targetRouterConfig && !targetRouterConfig.auth && !isLogin){
const { component } = targetRouterConfig;
return <Route exact path={pathname} component={component} />
}
if(isLogin){
// 如果是登陆状态,想要跳转到登陆,重定向到主页
if(pathname === '/login'){
return <Redirect to='/' />
}else{
// 如果路由合法,就跳转到相应的路由
if(targetRouterConfig){
return <Route path={pathname} component={targetRouterConfig.component} />
}else{
// 如果路由不合法,重定向到 404 页面
return <Redirect to='/404' />
}
}
}else{
// 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆
if(targetRouterConfig && targetRouterConfig.auth){
return <Redirect to='/login' />
}else{
// 非登陆状态下,路由不合法时,重定向至 404
return <Redirect to='/404' />
}
}
}
}