vue实现导航跳转
vue-router 基本跳转方法
在 Vue 项目中通过 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
声明式导航跳转
在模板中使用 <router-link> 组件实现跳转:
<template>
<router-link to="/">首页</router-link>
<router-link to="/about">关于</router-link>
</template>
可通过 active-class 指定激活状态的样式类名:
<router-link to="/about" active-class="active-link">关于</router-link>
编程式导航跳转
在组件方法中使用 router.push() 实现跳转:

methods: {
goToAbout() {
this.$router.push('/about')
}
}
带参数的跳转方式:
// 路径写法
this.$router.push('/user/123')
// 对象写法
this.$router.push({ path: '/user', query: { id: 123 } })
// 命名路由写法(需在路由配置中设置name)
this.$router.push({ name: 'user', params: { id: 123 } })
路由传参方式
通过动态路由传递参数:
// 路由配置
{ path: '/user/:id', component: User }
// 组件中获取
this.$route.params.id
通过查询参数传递:

// 跳转时
this.$router.push({ path: '/search', query: { keyword: 'vue' } })
// 组件中获取
this.$route.query.keyword
导航守卫控制
全局前置守卫示例:
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()
}
}
路由懒加载优化
使用动态导入实现路由懒加载:
const User = () => import('../views/User.vue')
const routes = [
{ path: '/user', component: User }
]






