useRouter

安装
pnpm i @huxy/router
使用
import {useRouter, Link, useRoute} from '@huxy/router';
useRouter
useRouter 是路由入口,传入路由配置信息,返回 页面元素 output、加载状态 loading、更新函数 updateRouter 等。
const {output, loading, updateRouter} = useRouter(routerCfgs);
入参信息
const others = {
projectKey: '123',
};
const input = {
browserRouter: false,
idKey: 'path',
childKey: 'children',
beforeRender: () => {},
afterRender: () => {},
basepath: '',
routers: [],
store: () => {},
inputPath: '',
inputParams: {},
title: 'test',
errorBoundary: null,
loading: null,
exact: false,
...others,
};
const {output} = useRouter(input);
这里传的配置为全局配置,单个路由信息配置可在路由表信息里面配置。
出参信息
const {
eventBus: {on, emit, off},
router: {push, replace},
store: {getState, setState, subscribe},
updateRouter,
output,
loading,
} = output;
例如:
const App = ({routerCfgs}) => {
const {output, loading, updateRouter} = useRouter(routerCfgs);
useEffect(() => {
const cancelLang = langStore.subscribe(async lang => {
storage.set('language', lang);
await getI18n();
updateRouter(getRouterCfgs());
});
return () => {
cancelLang();
};
}, []);
return (
<>
{output}
{loading && <Spinner global />}
</>
);
};
updateRouter 可更新整个路由配置。
路由表配置
const routers = {
path: '',
name: '',
icon: '',
redirect: '',
children: [],
component: '',
denied: false,
hideMenu: false,
resolve: null,
loadData: null,
title: 'test',
errorBoundary: null,
loading: null,
exact: false,
...others,
};
默认进入第一个路径,也可自行设置,如通过 redirect 设置默认进入到指定路径。
exact 为 true 是使用绝对路径,默认为 false,会带入 basepath 和父路径。
path 提供动态路由,如:/a/:id/:name 。
页面路由信息
每个路由都注册了一些基本信息,如:路由操作 router、前进后退 history、状态管理 store、当前面包屑 current、传入路径 inputPath、传入参数 params 等。也会将当前路由特定配置返回。
const {
eventBus: {on, emit, off},
router: {push, replace},
store: {getState, setState, subscribe},
updateRouter,
history: {getState, back, forward, go},
current,
inputPath,
path,
params,
name,
basepath,
children,
open,
active,
} = props;
push & replace
router.push('/a/b/c');
router.push({
path: '/a/b/c',
params: {id: 123},
query: {name: 'aaa'},
state: {uid: '000'},
});
router.push('./b/c');
replace 同 push 。
history
- getState:获取
history.state 。
- go:跳转。
- forward:前进。
- back:后退。
Link
<Link {...props} />
Link 属性
const props = {
to: '',
onClick,
preventDefault: false,
stopPropagation: true,
exact: true,
children,
target: null,
disabled: false,
...rest,
};
to 属性配置
to = '/a/b/c';
to = {
path: '/a/b/c',
params: {id: 123},
query: {name: 'aaa'},
state: {uid: '000'},
};
to = './b/c';
同 push 。
useRoute
const routerCfgs = useRoute();
返回当前路由的配置信息,同 页面路由信息,路由改变时会触发配置信息的更新。