vue实现router案例
Vue Router 基础实现案例
安装 Vue Router 依赖包
npm install vue-router
创建路由配置文件(通常为 src/router/index.js)
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import About from '../views/About.vue'
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
在 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')
创建路由视图组件
Home.vue 示例
<template>
<div>
<h1>Home Page</h1>
<router-link to="/about">Go to About</router-link>
</div>
</template>
About.vue 示例
<template>
<div>
<h1>About Page</h1>
<router-link to="/">Go to Home</router-link>
</div>
</template>
在 App.vue 中添加路由出口
<template>
<div id="app">
<router-view/>
</div>
</template>
动态路由实现
修改路由配置

{
path: '/user/:id',
name: 'User',
component: () => import('../views/User.vue')
}
User.vue 组件中获取参数
<template>
<div>
<h1>User ID: {{ $route.params.id }}</h1>
</div>
</template>
编程式导航
在组件方法中使用
methods: {
goToAbout() {
this.$router.push('/about')
},
goToUser(id) {
this.$router.push({ name: 'User', params: { id } })
}
}
路由守卫示例
全局前置守卫

router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
路由独享守卫
{
path: '/profile',
name: 'Profile',
component: Profile,
beforeEnter: (to, from, next) => {
// 验证逻辑
}
}
嵌套路由配置
父路由配置
{
path: '/dashboard',
component: Dashboard,
children: [
{
path: '',
component: DashboardHome
},
{
path: 'settings',
component: DashboardSettings
}
]
}
父组件模板
<template>
<div>
<h1>Dashboard</h1>
<router-view/>
</div>
</template>






