vue实现路线导航
Vue 实现路由导航的方法
使用 Vue Router 基本配置
安装 Vue Router 依赖:
npm install vue-router
在项目中配置路由(以 Vue 3 为例):
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
在 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 to="/">Home</router-link>
<router-link to="/about">About</router-link>
编程式导航(脚本中使用):
// 基本跳转
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)
this.$router.go(-1)
动态路由匹配
定义带参数的路由:
const routes = [
{ path: '/user/:id', component: User }
]
获取路由参数:
this.$route.params.id
导航守卫
全局前置守卫:
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')
}
]
路由元信息
定义路由 meta 字段:
const routes = [
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true }
}
]
在导航守卫中访问:
router.beforeEach((to, from, next) => {
if (to.meta.requiresAuth) {
// 权限校验逻辑
}
})






