在vue实现路由跳转
路由跳转的实现方法
在Vue中实现路由跳转主要通过Vue Router完成。以下是几种常见的路由跳转方式:
声明式导航
使用<router-link>组件实现跳转,适合模板中使用:
<router-link to="/home">Home</router-link>
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
编程式导航
通过this.$router实例方法实现跳转:
// 字符串路径
this.$router.push('/home')
// 对象形式
this.$router.push({ path: '/home' })
// 命名路由
this.$router.push({ name: 'user', params: { userId: '123' }})
// 带查询参数
this.$router.push({ path: '/register', query: { plan: 'private' }})
路由传参方式
params传参 适合传递敏感数据,不会显示在URL中:
// 跳转时传递
this.$router.push({ name: 'user', params: { id: 1 } })
// 接收参数
this.$route.params.id
query传参 参数会显示在URL中:
// 跳转时传递
this.$router.push({ path: '/user', query: { id: 1 } })
// 接收参数
this.$route.query.id
动态路由匹配
在路由配置中使用动态字段:
const routes = [
{ path: '/user/:id', component: User }
]
路由守卫控制跳转
可以使用导航守卫控制路由跳转:
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requiresAuth)) {
// 需要登录的路由
if (!auth.loggedIn()) {
next({ path: '/login' })
} else {
next()
}
} else {
next()
}
})
命名路由和命名视图
配置命名路由方便跳转:
const routes = [
{
path: '/user/:userId',
name: 'user',
component: User
}
]
使用命名视图实现复杂布局:
<router-view name="header"></router-view>
<router-view></router-view>
<router-view name="footer"></router-view>
路由懒加载
优化性能使用懒加载:
const User = () => import('./views/User.vue')
const routes = [
{ path: '/user', component: User }
]






