vue实现路由导航
Vue 路由导航的实现
Vue 中实现路由导航通常使用 Vue Router 库。以下是具体实现方法:
安装 Vue Router 在项目中安装 Vue Router 依赖:
npm install 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: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
]
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
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')
路由导航方式
声明式导航
在模板中使用 <router-link> 组件:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
编程式导航 在组件方法中使用:
// 普通导航
this.$router.push('/about')
// 带参数导航
this.$router.push({ name: 'About', params: { id: 123 } })
// 替换当前路由(不保留历史记录)
this.$router.replace('/about')
// 前进/后退
this.$router.go(1) // 前进一步
this.$router.go(-1) // 后退一步
路由参数处理
定义带参数的路由
{
path: '/user/:id',
name: 'User',
component: User
}
获取路由参数 在组件中访问:
this.$route.params.id
导航守卫
全局前置守卫
router.beforeEach((to, from, next) => {
// 进行权限验证等操作
next()
})
路由独享守卫
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 路由进入前的逻辑
next()
}
}
组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 组件渲染前调用
next()
},
beforeRouteUpdate(to, from, next) {
// 路由改变但组件复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 离开路由时调用
next()
}
}
路由懒加载
通过动态导入实现路由懒加载:
const User = () => import('../views/User.vue')
{
path: '/user',
component: User
}
嵌套路由
实现嵌套路由:
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
在父路由组件中添加 <router-view> 显示子路由:
<div>
<h2>User</h2>
<router-view></router-view>
</div>
以上方法涵盖了 Vue 中路由导航的主要实现方式,可根据项目需求选择适合的方案。







