×

Vue应用之路由跳转方式:push,replace和go

作者:Terry2022.12.16来源:Web前端之家浏览:3227评论:0
关键词:vuejs

Vue应用之路由跳转方式:push,replace和go。

在浏览器中,点击链接实现导航的方式,叫做声明式导航。例如:普通网页中点击 a标签链接。vue项目中点击router-link标签链接都属于声明式导航。
在浏览器中,调用API方法实现导航的方式,叫做编程式导航。例如:普通网页中调用location.href跳转到新页面的方式,属于编程式导航。vue项目中编程式导航有this.$router.push(),this.$router.replace(),this.$router.go()。

声明式导航router-link

1. 不带参数

<router-link :to="{name:'home'}"> 
<router-link :to="{path:'/home'}"> 
// name,path都行, 建议用name  
// 注意:router-link中链接如果是'/'开始就是从根路由开始,如果开始不带'/',则从当前路由开始。

2.带参数

<router-link :to="{name:'home', params: {id:1}}">  
 
// params传参数 (类似post)
// 路由配置 path: "/home/:id" 或者 path: "/home:id" 
// 不配置path ,第一次可请求,刷新页面id会消失
// 配置path,刷新页面id会保留
 
// html 取参  $route.params.id
// script 取参  this.$route.params.id
 
 
<router-link :to="{name:'home', query: {id:1}}"> 
 
// query传参数 (类似get,url后面会显示参数)
// 路由可不配置
 
// html 取参  $route.query.id
// script 取参  this.$route.query.id

编程式导航

1、this.$router.push

跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面:

在这里插入代码片// 字符串
this.$router.push('index') 

// 对象
this.$router.push({path: 'login-pw'})

// 带参数
this.$router.push({path: 'login-pw', query: {'account': this.account.account}})

// 跳转后的页面获取参数
this.account.account = this.$route.query.account

2、this.$router.replace

1.跳转到指定的URL,替换history栈中最后一个记录,点击后退会返回至上一个页面。(A----->B----->C 结果B被C替换 A----->C)
2.设置replace属性(默认值:false)的话,当点击时,会调用router.replace(),而不是router.push(),于是导航后不会留下history记录。
3.即使点击返回按钮也不会回到这个页面。加上replace: true时,它不会向 history 添加新纪录,而是跟它的方法名一样——替换当前的history记录。

// 声明式
<reouter-link :to="..." replace></router-link>
// 编程式:
router.replace(...)
// push方法也可以传replace
this.$router.push({path: '/homo', replace: true})


onConfirm: () => {
  this.$router.replace('/TravelManage')
}

3、this.$router.go(n)

1.向前或者向后跳转n个页面,n可为正整数或负整数

2.this.$router.go(1) // 类似history.forward()

3.this.$router.go(-1) // 类似history.back()

三者区别:

this.$router.push

跳转到指定url路径,并想history栈中添加一个记录,点击后退会返回到上一个页面

this.$router.replace

跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上上个页面 (就是直接替换了当前页面)

this.$router.go(n)

向前或者向后跳转n个页面,n可为正整数或负整数。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/vuejs20221216a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: