vue 路由实现
Vue 路由实现方法
安装 Vue Router
使用 npm 或 yarn 安装 Vue Router 依赖包:
npm install vue-router
# 或
yarn add vue-router
基本路由配置
在项目中创建路由配置文件(如 router/index.js),定义路由规则:
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
挂载路由到 Vue 实例
在 main.js 中引入并挂载路由:
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
路由视图与导航
在组件模板中使用 <router-view> 和 <router-link>:
<template>
<div>
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
<router-view></router-view>
</div>
</template>
动态路由匹配
通过冒号 : 定义动态路径参数:

const routes = [
{ path: '/user/:id', component: User }
]
在组件中通过 $route.params 访问参数:
export default {
computed: {
userId() {
return this.$route.params.id
}
}
}
嵌套路由
使用 children 属性定义嵌套路由:
const routes = [
{
path: '/user',
component: User,
children: [
{ path: 'profile', component: Profile },
{ path: 'posts', component: Posts }
]
}
]
父组件模板中需要嵌套 <router-view>:

<template>
<div>
<h2>User Page</h2>
<router-view></router-view>
</div>
</template>
编程式导航
通过 router 实例方法实现导航:
// 字符串路径
router.push('/about')
// 对象形式
router.push({ path: '/about' })
// 带查询参数
router.push({ path: '/search', query: { q: 'vue' } })
// 替换当前路由
router.replace({ path: '/home' })
// 前进/后退
router.go(1)
router.go(-1)
路由守卫
实现全局或路由独享的导航守卫:
// 全局前置守卫
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
// 路由独享守卫
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 验证逻辑
}
}
]
路由懒加载
使用动态导入实现组件懒加载:
const routes = [
{
path: '/dashboard',
component: () => import('./views/Dashboard.vue')
}
]






