vue实现路由导航
Vue 路由导航实现方法
在 Vue 中实现路由导航主要通过 Vue Router 完成。以下是几种常见的路由导航方式:
安装 Vue Router
npm install vue-router
基本路由配置
在项目入口文件(通常是 main.js 或 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
})
app.use(router)
声明式导航
使用 <router-link> 组件实现导航:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
可以添加 active 类样式:
<router-link to="/about" active-class="active-link">About</router-link>
编程式导航
通过 router 实例的方法进行导航:
// 字符串路径
this.$router.push('/about')
// 带参数
this.$router.push({ path: '/user', query: { id: '123' } })
// 命名路由
this.$router.push({ name: 'user', params: { userId: '123' } })
// 替换当前路由(不留下历史记录)
this.$router.replace('/login')
// 前进/后退
this.$router.go(1) // 前进1步
this.$router.go(-1) // 后退1步
路由参数传递
动态路由匹配
const routes = [
{ path: '/user/:id', component: User }
]
访问参数:
this.$route.params.id
查询参数
this.$router.push({ path: '/search', query: { q: 'vue' } })
访问查询参数:
this.$route.query.q
导航守卫
全局前置守卫
router.beforeEach((to, from, next) => {
// 验证逻辑
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
路由独享守卫
const routes = [
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 验证逻辑
}
}
]
组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 组件渲染前调用
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但组件复用时调用
},
beforeRouteLeave(to, from, next) {
// 离开路由时调用
}
}
嵌套路由
配置嵌套路由:
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
]
在父组件中添加 <router-view>:
<div class="user">
<h2>User {{ $route.params.id }}</h2>
<router-view></router-view>
</div>
路由懒加载
优化性能的路由懒加载方式:
const routes = [
{
path: '/about',
component: () => import('./views/About.vue')
}
]
命名视图
同一路由展示多个视图:
const routes = [
{
path: '/',
components: {
default: Home,
sidebar: Sidebar,
footer: Footer
}
}
]
对应模板:
<router-view name="sidebar"></router-view>
<router-view></router-view> <!-- 默认视图 -->
<router-view name="footer"></router-view>
以上方法涵盖了 Vue 路由导航的主要使用场景,可以根据项目需求选择适合的方式实现路由导航功能。







