所谓编程式导航,就是在js中做跳转链接。
之前用router-link做跳转链接
<router-link to='/path'>
还可以用router的实例方法,做跳转
router.push()
router.push原理:
这个方法,会向 history栈 添加一个新纪录,之前<router-link>,在内部也是调用了此方法,用户点击浏览器后退按钮时,会返回到之前的URL。
router.push()参数
此方法参数写法有四种方式:
(1)字符串
this.$router.push('/play') //参数是字符串,/ 可写可不写
(2)对象形式
this.$router.push({path:'/play'}) // 对象形式,path对应路径,/ 可写可不写
(3)命名的路由
this.$router.push({name:'play',params:{userId:'123'}}) // 对象形式,name是路由name名字,后边params是可携带参数,通过 this.$route.parmas 可以拿到携带的参数。
也可以:this.$router.push({name:'play',query:{userId:'123'}}) ,通过 this.$route.query 可以拿到路径中的参数
(4)对象形式
this.$router.push({path:'/play',query:{user:'lxc',pas:123456}}) //path对应路径,后边query是携带的关键字,如果用此参数,路径会变成: localhost:8080/#/play?user=lxc&pas=123456,通过 this.$route.query 可以拿到路径中的参数
tips:
1> 使用命名路由后边携带参数的key可以是params,也可以是query,只不过取参数形式不同。
2> 使用path时,后边携带的参数的key不可以为params,否则不会生效!!!
// 无效的写法 router.push({ path: '/user', params: { userId }})
<router-link>同上!!!
其他写法都不会生效。上边name为路由的名字,在路由配置中,需要给路由加上名字:
const router = new VueRouter({
routes:[
{
path:'/play',
name:'play',
component:play
}
]
})
命名路由
可以在路由配置中,给路由添加名字,它的作用是:
(1)路由跳转时,可以用name路由名字作为路由跳转的路径
<router-link :to='{name:"user",params:{id:1}}'>
// 等同于
this.$router.push({name:'user',params:{id:1}})
router.replace()
与router.push唯一的不同是:router.replace不会向history添加新纪录,而是替换掉当前的history记录(也就是替换当前路径)
router.go(n)
这个方法参数是一个整数,在history记录中,向前或向后回退多少步(与window.history.go类似)。
this.$router.go(1) //向前跳转一页
this.$router.go(-1) //向后跳转一页