Vue Router 编程式导航

编程式导航

除了使用<router-link>创建a标签来定义导航链接,还可以借助router的实例方法,通过编写代码来实现

导航到不同的位置

在Vue实例中,可以通过$router访问路由实例,因此可以调用this.$router.push 导航到不同的URL。

this.$router.push会向history栈添加一个新的记录,当用户点击浏览器后退按钮时,会回到之前的URL。

当点击<router-link>时,内部也会调用这个方法,所以点击<router-link to='...'>相当于调用this.$router.push(...)

<router-link to='...'>是声明式导航,而this.$router.push(...)是编程式导航。

this.$router.push(...)的参数

该方法的参数可以是一个字符串路径,或者一个描述地址的对象。

1.字符串

this.$router.push('/users/eduardo');

url:/users/eduardo

2.带有path的对象

this.$router.push({path: '/users/eduardo'});

url:/users/eduardo

3.name+params(动态段参数)组成的对象(让路由自己建立url)

this.$router.push({name: 'user', params: {username: 'eduardo'}});

通过name找到对应路由的path,通过params的key找到path中动态段,用value替换,建立url。

url:/users/eduardo

4.path+query(查询参数)

this.$router.push({path: '/register', query: {plan: 'private'}});

url:/register?plan=private

5.path+hash

this.$router.push({path: '/about', hash: '#team'});

url:/about#team

注:path和params放在一起,会自动忽略params

属性to和this.$router.push接受的对象种类相同,所以两者规则完全相同

this.$router.push和所有其他导航方法都会返回一个Promise,让我们可以等到导航完成后才知道是成功还是失败。

替换当前位置

作用类似this.$router.push,唯一不同的是,它在导航时不会向history添加新记录,它取代了当前的条目。

<router-link to='...' replace>是声明式导航,this.$router.replace(...)是编程式导航。

也可以直接在传递给this.$router.push()的routeLocation(导航实例)中增加一个属性replace:true:

this.$router.push({path: '/users/eduardo',replace:true});

相当于:

this.$router.replace({path: '/users/eduardo'});

横跨历史 this.$router.go()

该方法采用一个整数作为参数,表示在history堆栈中前进或后退多少步,类似于window.history.go(n)。

this.$router.go(1);

相当于this.$router.forward()

this.$router.go(-1);

相当于this.$router.back()

如果go前进/后退的记录数超出了已存在的记录数,则静默失败。

篡改历史

Vue Router 模仿window.history API
this.$router.push window.history.pushState
this.$router.replace window.history.replaceState
this.$router.go window.history.go

无论在创建路由器实例时传递什么样的history配置,Vue Router的导航方法(push、replace、go)都能始终如一地工作。

posted @ 2021-10-17 15:20  慕斯星球  阅读(257)  评论(0)    收藏  举报