umi 路由配置
作者: 时间:2023-09-22阅读数:人阅读
一、基础路由
- 项目根目录下新建文件夹:config/routes.tsx (umi约定,位置不能错,不然引入会报错)
- routes.tsx
import type { IRoute } from 'umi';
const routes: IRoute[] = [
{ path: '/', component: '@/pages/index' }
];
export default routes;
-
.umirc.ts这个文件内引入
简单介绍下这个文件:umi的配置文件,参考官方文档
import { defineConfig } from 'umi';
import routes from './config/routes';
export default defineConfig({
nodeModulesTransform: {
type: 'none',
},
// 设置hash地址
history: {
type: 'hash'
},
routes: [
...routes
],
fastRefresh: {},
});
- 全局路由layouts
-
src下新建文件夹layouts/index.tsx
-
再新建几个页面
-
children就是子页面的输出,类似vue的router-view
-
页面建好后,下面是layouts和routes的配置
layouts/index.tsx
import type { IRouteComponentProps } from 'umi';
import Header from '@/components/Header';
import LeftMenu from '@/components/LeftMenu';
const Layout = ({ children }: IRouteComponentProps) => {
return (
<>
<Header />
<div className='flex flex-1'>
<LeftMenu />
<div className="flex-1">
{ children }
</div>
</div>
</>
);
};
export default Layout;
config/routes.tsx
import type { IRoute } from 'umi';
const routes: IRoute[] = [
{ path: '/login', component: '@/pages/login' },
{ path: '/', component: '@/layouts/index', exact: false,
routes: [
{ path: '/', component: '@/pages/home', exact: true },
{ path: '/personal', component: '@/pages/personal', exact: true },
/* 动态路由 */
{ path: '/details/:id?', component: '@/pages/details/[id$]', exact: true },
{ component: '@/pages/404' },
],
},
];
export default routes;
- 动态路由简单配置,项目中可加可不加, routes里的配置看上面代码块
-
新建details页面,文件名(以id为地址栏参数):[id$].tsx
-
跳转方法
history.push(`/details/${123}`);
- 页面内获取地址栏参数
import { useParams } from 'umi';
const Details = () => {
const { id } = useParams<any>();
console.log(id); // 123
return (
<div>详情页动态路由</div>
);
};
export default Details;
- 页面效果
本站所有文章、数据、图片均来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:licqi@yunshuaiweb.com
下一篇:Uncaught SyntaxError: The requested module ‘/node_modules/.vite/deps/vue.js?v=3e1adf4e‘ does not ...