vue中实现跳转
vue-router 基本跳转方法
在 Vue 项目中实现页面跳转主要依赖 vue-router 库。安装路由依赖后,可以通过以下方式实现跳转:
npm install vue-router
声明式导航
使用 <router-link> 组件实现跳转,适合模板中的链接式跳转:
<router-link to="/home">首页</router-link>
<router-link :to="{ name: 'user', params: { userId: 123 }}">用户页</router-link>
编程式导航
在 JavaScript 代码中使用路由实例方法:
// 字符串路径
this.$router.push('/home')
// 带参数的对象形式
this.$router.push({ path: '/user/123' })
// 命名路由
this.$router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数
this.$router.push({ path: '/register', query: { plan: 'private' }})
路由传参方式
通过 params 传递参数:
// 定义路由
{
path: '/user/:userId',
name: 'user',
component: User
}
// 跳转时传递
this.$router.push({ name: 'user', params: { userId: 123 }})
通过 query 传递参数:
this.$router.push({ path: '/user', query: { userId: 123 }})
替换当前路由
使用 replace 方法不会留下历史记录:
this.$router.replace('/login')
路由重定向
在路由配置中设置重定向:
{
path: '/old-path',
redirect: '/new-path'
}
导航守卫
实现路由跳转前后的控制逻辑:
router.beforeEach((to, from, next) => {
// 跳转前逻辑
next()
})
router.afterEach((to, from) => {
// 跳转后逻辑
})
动态路由匹配
处理相似路径的多个路由:
{
path: '/user/:id',
component: User
}
在组件中通过 this.$route.params.id 获取参数。
路由懒加载
优化大型应用的路由加载性能:
const User = () => import('./views/User.vue')
路由模式设置
根据需求选择路由模式:
const router = new VueRouter({
mode: 'history', // 或 'hash'
routes
})






