vue静态路由实现方式
静态路由的基本配置
在Vue项目中,静态路由通常通过vue-router库实现。安装依赖后,在router/index.js文件中定义路由数组,每个路由对象包含path和component属性,用于映射路径与组件。
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
路由懒加载优化
通过动态导入语法实现组件懒加载,提升首屏加载性能。使用import()函数返回Promise,Vue Router会自动处理按需加载。
const routes = [
{ path: '/', component: () => import('../views/Home.vue') },
{ path: '/about', component: () => import('../views/About.vue') }
]
嵌套路由配置
通过children属性实现嵌套路由,父组件需包含<router-view>占位符。嵌套路径会自动拼接父路径。

const routes = [
{
path: '/user',
component: () => import('../views/User.vue'),
children: [
{ path: 'profile', component: () => import('../views/UserProfile.vue') },
{ path: 'settings', component: () => import('../views/UserSettings.vue') }
]
}
]
路由参数传递
静态路径中可通过冒号定义动态参数,组件通过$route.params访问。参数会匹配/user/123形式的路径。
const routes = [
{ path: '/user/:id', component: () => import('../views/UserDetail.vue') }
]
路由元信息配置
通过meta字段添加路由元信息,常用于权限控制或页面标题设置。可在导航守卫中访问这些数据。

const routes = [
{
path: '/admin',
component: () => import('../views/Admin.vue'),
meta: { requiresAuth: true }
}
]
路由重定向与别名
使用redirect实现路径重定向,alias定义路径别名。两者均可实现多路径映射同一组件。
const routes = [
{ path: '/home', redirect: '/' },
{ path: '/', component: Home, alias: '/welcome' }
]
404页面处理
通过通配符路径捕获未匹配路由,通常放在路由配置末尾。需注意路由匹配优先级规则。
const routes = [
// ...其他路由
{ path: '/:pathMatch(.*)*', component: () => import('../views/NotFound.vue') }
]






