除了使用
router.push( location, onComplete?,onAbort)
注意:在Vue实力内部,你可以通过 **$router 访问路由实例,因此你可以调用 this.$router.push
想要导航到不同的 URL,则使用 router.push** **方法。这个方法会向 history 栈添加一个新的记录,所以,当用户 点击浏览器后退按钮时,则回到之前的 URL。
当你点击
| 声明式 | 编程式 |
|---|---|
| <**router-link :to=”…”>** | router.push(…) |
该方法的参数可以时一个字符串路径,或者一个描述地址的对象。例如:
// 字符串router.push( 'home')// 对象router.push({ path:'home'})// 命名的路由router.push({ name: 'user',params: {userId:'123'}})// 带查询参数,变成 /register?plan=privaterouter.push({ path:'register',query:{plan:'private'}})
注意:如果提供了 path,params 会被忽略,上述例子中的 **query 并不属于这种情况,取而代之的是下面例子的做法,你需要提供路由的 name 或手写完整的带有参数的 path**
const userId = '123'router.push({ name:'user',params:{userId}}) // -> /user/123router.push({ path:`/user/${userId}`}) // -> /user/123// 这里的 params 不生效router.push({ path:'/user',params:{ userId }}) // ->/user
router.replace( location, onComplet?, onAbort)
跟 router.push 很想,唯一的不同就是,它不会向history 添加新纪录,而是跟它的方法名一样,——替换掉当前的history 记录
| 声明式 | 编程式 |
|---|---|
| router.repalce(…) |
router.go( n )
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
例子:
// 在浏览器记录中 前进一步,等同于 history。forward()router.go(1)// 后退一步记录,等同于 history.back()router.go(-1)// 前进 3步记录router.go(3)// 如果 history 记录不够用,那就默默地失败router.go(-100)router.go(100)
操作 History
你也许注意到 router.push、router.replace、和 router.go 跟window.history.pushState、window.history.replaceState 和 window.history.go 好像,实际上它们确实是效仿 window.history API的
因此,如果你已经熟悉 browser history APIs,那么在 Vue Router 中操作 history 就是超级简单的。
还有值得提及的 Vue Router 的导航方法 push replace go 在各类路由模式( history 、 hash 和 abstract ) 下表现一致
