如还不知如何安装与引入 router4x
,请先看此篇。配置文件在路径 src/router/index.ts
下。
建议路由页 .vue 文件全部放在 scr/views 下。
根据需求不同,总结了如下3类配置:
1. 普通配置
方式一
import { createRouter, createWebHashHistory } from 'vue-router'
import index from '../views/index.vue'
import home from '../views/home.vue'
import about from '../views/about.vue'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
name: 'index',
component: index
},
{
path: '/home',
name: 'home',
component: home
},
{
path: '/about',
name: 'about',
component: about
}
]
});
export default router
方式二
import { createRouter, createWebHashHistory } from 'vue-router'
// 创建路由实例并传递 `routes` 配置
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
name: 'index',
component: () => import('../views/index.vue')
},
{
path: '/home',
name: 'home',
component: () => import('../views/home.vue')
},
{
path: '/about',
name: 'about',
component: () => import('../views/about.vue')
}
]
});
export default router
2. 懒加载
方式一:使用 defineAsyncComponent 方法
import { defineAsyncComponent } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
// 懒加载:defineAsyncComponent 方法
const _import = (path:any) => defineAsyncComponent(() => import(`../views/${path}.vue`));
const routes = [
{
path: '/',
name: 'index',
component: _import('index'),
},
{
path: '/about',
name: 'about',
component: _import('about'),
},
{
path: '/home',
name: 'home',
component: _import('home'),
}
];
// 创建路由实例并传递 `routes` 配置
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router
方式 二:使用 import.meta.glob
import { createRouter, createWebHashHistory } from 'vue-router'
// 懒加载:import.meta.glob,注意双 * 表示获取 views 下及其子文件夹的 .vue 文件
const modules = import.meta.glob('../views/**/*.vue');
// 如果仅获取 views 文件夹的 .vue 文件,且不包含子文件,可这样写
// const modules = import.meta.glob('../views/*.vue');
// 定义路由
const routes = Object.keys(modules).map((key) => {
let path = key.split('views/')[1].split('.vue')[0];
let item = {
name: path,
path: `/${path}`,
/* @vite-ignore */
component: () => import(key)
}
return item;
})
// 创建路由实例并传递 `routes` 配置
const router = createRouter({
history: createWebHashHistory(),
routes
});
export default router
3. 二级路由
import { createRouter, createWebHashHistory } from 'vue-router'
const childRoutes = [
{
name: 'home',
path: `home`,
component: () => import('../views/home.vue')
},
{
name: 'about',
path: 'about',
component: () => import('../views/about.vue')
}
]
// 创建路由实例并传递 `routes` 配置
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
name: 'index',
component: () => import('../views/index.vue'),
redirect: childRoutes[0].path, // 设置默认打开的页面
children: childRoutes
}
]
});
export default router