vue 实现路径
在 Vue 中实现路径管理通常涉及路由配置、动态路由、嵌套路由等场景,以下是具体实现方法:
基础路由配置
安装 Vue Router 并创建路由实例:
npm install vue-router
在项目中定义路由:
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
})
动态路径参数
通过冒号 : 定义动态段:
{
path: '/user/:id',
component: User,
props: true // 将参数作为 props 传递
}
在组件中通过 $route.params.id 或 props 接收参数。
嵌套路由
使用 children 属性实现嵌套视图:

{
path: '/parent',
component: Parent,
children: [
{ path: 'child', component: Child }
]
}
父组件需包含 <router-view> 作为子组件出口。
编程式导航
通过 router 实例方法控制跳转:
// 字符串路径
router.push('/users/1')
// 带参数对象
router.push({ path: '/users', query: { page: 2 } })
// 命名路由
router.push({ name: 'user', params: { id: 1 } })
路由守卫
实现导航控制逻辑:

router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
路由元信息
通过 meta 字段附加数据:
{
path: '/admin',
meta: { requiresAuth: true }
}
懒加载路由
使用动态导入提升性能:
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue')
}
滚动行为
自定义页面切换后的滚动位置:
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
return savedPosition || { top: 0 }
}
})
路由模式切换
根据需求选择历史模式或哈希模式:
createWebHistory() // 无#的HTML5模式
createWebHashHistory() // 带#的哈希模式






