关于Vue路由的跳转方式

声明式导航

1. <router-link :to="...">

router-link 组件支持用户在具有路由功能的应用中 (点击) 导航。 通过 to 属性指定目标地址,默认渲染成带有正确链接的 a 标签,可以通过配置 tag 属性生成别的标签.

不带参数:

<!-- 通过name(建议使用) --> <router-link :to="{name: 'home'}">
 <!-- 通过path --> <router-link :to="{path: '/home'}">

携带参数:

query 传参(类似get,参数显示在URL后面)
<router-link :to="{name:'home', query: {a: 1}}">
跳转页面获取参数:
$route.query.a

script中:

this.$route.query.a
params 传参(类似post)
<!-- 如果提供了path,params会被忽略,所以只能通过name --> <router-link :to="{name:'home', params: {b: 2}}">
需要路由配置

router.js:

path: "/home/:b"
跳转页面获取参数:

html中:

$route.params.b

script中:

this.$route.params.b

2. <router-link :to="..." replace>

用法和 <router-link :to="..."> 一样
区别:

<router-link :to="...">会向history中添加新记录,点击浏览器后退按钮时,会回到上一个页面,等同于 window.history.pushState <router-link :to="..." replace>不会向history中添加新记录,而是会替换掉当前的history记录,等同于 window.history.replaceState

编程式导航

1. router.push(...)

不带参数:

//通过name this.$router.push({name: 'home'}) 
//通过path this.$router.push({path: '/home'}) 
//简写 this.$router.push('/home')

携带参数:

query 传参(类似get,参数显示在URL后面)
this.$router.push({name:'home', query: {a: 1}}) this.$router.push({path:'/home', query: {a: 1}})
跳转页面获取参数:

html中:

$route.query.a

script中:

this.$route.query.a
params 传参(类似post)
//如果提供了path,params会被忽略,所以只能通过name this.$router.push({name:'home', params: {b: 2}})
需要路由配置

router.js:

path: "/home/:b"
跳转页面获取参数:

html中:

$route.params.b

script中:

this.$route.params.b

2. router.replace(...)

用法和 router.push(...) 一样
区别:

router.push(...)会向history中添加新记录,点击浏览器后退按钮时,会回到上一个页面,等同于 window.history.pushState router.replace(...)不会向history中添加新记录,而是会替换掉当前的history记录,等同于 window.history.replaceState

3. router.go(n)

参数n是一个整数,指定在history中前进或后退n步,等同于window.history.go(n)
//在history中前进一步,等同于router.forward() this.$router.go(1)
 //在history中后退一步,等同于router.back() this.$router.go(-1)
 //刷新当前页面 this.$router.go(0)

4. router.forward()

在history中前进一步,等同于router.go(1)

5. router.back()

在history中后退一步,等同于router.go(-1)

总结:

router-link 当被点击后,内部会立刻把 to 的值传到 router.push(),等同于调用 router.push()

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值