vue路由实现切换
Vue 路由切换的实现方法
Vue Router 是 Vue.js 官方的路由管理器,用于实现单页应用(SPA)中的页面切换。以下是常见的路由切换方式:
声明式导航
使用 <router-link> 组件实现路由切换,通过 to 属性指定目标路由路径:
<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>
可以通过 tag 属性指定渲染的标签类型:
<router-link to="/profile" tag="button">Profile</router-link>
编程式导航
在 Vue 组件中通过 this.$router 提供的 API 实现路由跳转:
// 跳转到指定路径
this.$router.push('/home')
// 带参数跳转
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)
路由传参
可以通过以下方式传递参数:

-
动态路由匹配:
// 路由配置 { path: '/user/:id', component: User } // 组件中获取 this.$route.params.id -
查询参数:
// 跳转时 this.$router.push({ path: '/search', query: { keyword: 'vue' } }) // 组件中获取 this.$route.query.keyword -
命名路由传参:

// 路由配置 { name: 'profile', path: '/profile/:userId', component: Profile } // 跳转时 this.$router.push({ name: 'profile', params: { userId: 123 } })
导航守卫
可以在路由切换前后执行逻辑:
// 全局前置守卫
router.beforeEach((to, from, next) => {
// 必须调用 next()
next()
})
// 路由独享守卫
{
path: '/admin',
component: Admin,
beforeEnter: (to, from, next) => {
// 验证逻辑
next()
}
}
// 组件内守卫
export default {
beforeRouteEnter(to, from, next) {
// 不能访问组件实例
next(vm => {
// 通过 vm 访问组件实例
})
},
beforeRouteUpdate(to, from, next) {
// 当前路由改变但组件被复用时调用
next()
},
beforeRouteLeave(to, from, next) {
// 导航离开时调用
next()
}
}
路由过渡效果
可以通过 <transition> 组件为路由切换添加动画:
<transition name="fade">
<router-view></router-view>
</transition>
<style>
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
路由懒加载
通过动态导入实现路由组件懒加载:
const User = () => import('./views/User.vue')
const router = new VueRouter({
routes: [
{ path: '/user', component: User }
]
})






