VUE中路由变化this.$router(push eplacegoack)
1.this.$router.push()
描述:跳转到指定url路径,并向history栈中添加一个记录,点击后退会返回到上一个页面。
// 1字符串 this.$router.push(/user/order) // 2对象 this.$router.push({ path: /user/order }) //3传参 this.$router.push({ path: /user/order, query: {id: 123} }) //3-1取参数 this.$route.query.id //4命名的路由 this.$router.push({ name: /user/order, params: {id: 123} }) //4-1取参数 this.$route.params.id
2.this.$router.replace()
描述:跳转到指定url路径,但是history栈中不会有记录,点击返回会跳转到上个页面 (直接替换当前页面)。
3.this.$router.go():原页面表单中的内容会丢失
this.$router.go(-1):后退+刷新; this.$router.go(0):刷新; this.$router.go(1) :前进
4.this.$router.back(): 原页表表单中的内容会保留;
this.$router.back(-1):后退 ; this.$router.back(0) 刷新; this.$router.back(1):前进
需求一: a页面 push到 b页面, b页面 push到 c页面,c页面 replace到 b页面,这时候点击按钮(router.go(-1)),没有效果,需点击两次才能返回到a页面中!
分析: 页面跳转流程: a => b => c => b 路由栈:a => b => b 就路由栈说明:栈中b页面替代了c页面,所以路由栈中不存在c路由,因此在我们在点击第一次返回后,其实是从一个b页面返回到另一个b页面
方案一: 在点击使用replace的代码后面添加一条路由返回的代码 (推荐使用)
this.$router.replace(/你的路由名字) this.$router.go(-1) //重点
query: { // replace: true }
存在的问题,如果当前页面通过replace页面生变化,那么返回上一级页面 fullPath会携带参数, 并且使用 this.$router.go(-1) 返回上一级页面时地址栏没参数,query中还是有携带的参数
方案二: 在点击后退的按钮处 添加判断,点击后还是当前页面,则再次后退
this.$router.go(-1) setTimeout(() => { if (this.$route.name === hello) { this.$router.go(-1) } }, 500)
list(列表页) add/update (新建页/编辑页) details (查看页)
需求二:list – add — details — list 问题:就是单据新增后提交审核,点击驳回,在点击右上角返回 页面返回的路径不对,返回到新建页面了(应该返回列表页)
解决方案:在 add 保存完数据后,跳转至 details 使用 this.$router.replace() 调转,不会记录路由,在由 details 页面返回会直接返回 list 页面
注意: replace 不会在路由中记录
下一篇:
5款超级好用的开发效率工具,建议收藏!