vue router怎么实现跳转
vue router 跳转方法
在 Vue Router 中实现页面跳转有多种方式,主要包括编程式导航和声明式导航两种形式。
编程式导航
使用 router.push 方法可以实现编程式导航跳转,该方法会向 history 栈添加一个新的记录。
// 字符串路径
this.$router.push('/home')
// 对象形式
this.$router.push({ path: '/home' })
// 带查询参数
this.$router.push({ path: '/home', query: { id: '123' } })
// 命名路由
this.$router.push({ name: 'user', params: { userId: '123' } })
使用 router.replace 方法会替换当前 history 记录而不是添加新记录。
this.$router.replace('/home')
使用 router.go 方法可以在 history 记录中前进或后退。

// 前进 1 步
this.$router.go(1)
// 后退 1 步
this.$router.go(-1)
声明式导航
在模板中使用 <router-link> 组件创建导航链接。
<!-- 基本用法 -->
<router-link to="/home">Home</router-link>
<!-- 对象形式 -->
<router-link :to="{ path: '/home' }">Home</router-link>
<!-- 命名路由 -->
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
<!-- 带查询参数 -->
<router-link :to="{ path: '/home', query: { id: '123' }}">Home</router-link>
路由传参
通过 params 传递参数需要在路由配置中定义参数名。

const router = new VueRouter({
routes: [
{ path: '/user/:userId', name: 'user', component: User }
]
})
通过 query 传递参数不需要在路由配置中定义。
this.$router.push({ path: '/home', query: { id: '123' } })
导航守卫
可以使用导航守卫在路由跳转前后执行特定逻辑。
router.beforeEach((to, from, next) => {
// 跳转前逻辑
next()
})
router.afterEach((to, from) => {
// 跳转后逻辑
})
动态路由
可以通过 addRoute 方法动态添加路由。
router.addRoute({ path: '/about', component: About })
以上方法涵盖了 Vue Router 中实现页面跳转的主要方式,可以根据具体需求选择合适的方法。






