vue实现路由导航
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: '/', 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'
createApp(App).use(router).mount('#app')
在根组件模板中添加 <router-view>:
<!-- App.vue -->
<template>
<router-view/>
</template>
声明式导航
使用 <router-link> 组件实现导航:
<router-link to="/">Home</router-link>
<router-link to="/about">About</router-link>
可通过 active-class 指定激活状态的样式类名:
<router-link to="/about" active-class="active">About</router-link>
编程式导航
通过 router 实例的方法进行导航:

// 在组件方法中
this.$router.push('/about') // 跳转到指定路径
this.$router.replace('/login') // 替换当前历史记录
this.$router.go(-1) // 返回上一页
组合式 API 中使用:
import { useRouter } from 'vue-router'
const router = useRouter()
router.push('/dashboard')
路由传参
通过动态路由传递参数:
// 路由配置
{ path: '/user/:id', component: User }
获取参数:
// 选项式 API
this.$route.params.id
// 组合式 API
import { useRoute } from 'vue-router'
const route = useRoute()
console.log(route.params.id)
通过查询参数传递:
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) {
// 在渲染该组件的对应路由被验证前调用
},
beforeRouteLeave(to, from, next) {
// 导航离开时调用
}
}
路由元信息
定义路由元数据:
{
path: '/admin',
component: Admin,
meta: { requiresAuth: true }
}
懒加载路由
优化性能的懒加载方式:
const User = () => import('../views/User.vue')
{
path: '/user',
component: User
}
嵌套路由
实现多级路由:
{
path: '/dashboard',
component: Dashboard,
children: [
{ path: 'profile', component: Profile },
{ path: 'settings', component: Settings }
]
}
需在父组件中添加 <router-view>:
<!-- Dashboard.vue -->
<template>
<div>
<h1>Dashboard</h1>
<router-view/>
</div>
</template>






