vue实现路由导航
Vue 路由导航实现方法
安装 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(),
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')
路由视图
在 App.vue 中添加路由视图:
<template>
<div id="app">
<router-view/>
</div>
</template>
导航方式
声明式导航(使用 <router-link>):
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
编程式导航(使用 router.push):
methods: {
goToAbout() {
this.$router.push('/about')
// 或使用命名路由
// this.$router.push({ name: 'About' })
}
}
路由传参
路径参数:
// 路由配置
{
path: '/user/:id',
name: 'User',
component: User
}
// 导航方式
this.$router.push('/user/123')
// 或
this.$router.push({ name: 'User', params: { id: 123 } })
查询参数:
this.$router.push({ path: '/search', query: { keyword: 'vue' } })
路由守卫
全局前置守卫:
router.beforeEach((to, from, next) => {
// 进行权限验证等操作
if (to.meta.requiresAuth && !isAuthenticated) {
next('/login')
} else {
next()
}
})
组件内守卫:
export default {
beforeRouteEnter(to, from, next) {
// 在渲染该组件的对应路由被验证前调用
next()
},
beforeRouteUpdate(to, from, next) {
// 在当前路由改变,但该组件被复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 导航离开该组件的对应路由时调用
next()
}
}
嵌套路由
配置嵌套路由:
const routes = [
{
path: '/user',
component: User,
children: [
{
path: 'profile',
component: UserProfile
},
{
path: 'posts',
component: UserPosts
}
]
}
]
在父组件中添加 <router-view>:
<template>
<div class="user">
<h2>User</h2>
<router-view/>
</div>
</template>
路由懒加载
优化性能,按需加载路由组件:

const User = () => import('../views/User.vue')
const routes = [
{
path: '/user',
name: 'User',
component: User
}
]






