好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

vue中$router.back()和$router.go()的用法

$router.back()和$router.go()

返回上一页,有两种方法:

1. $router.back()

2. $router.go()

使用$router.back()和$router.go(-1)作用相同,都是返回原页面,但如果原页面路由携带参数,使用以上两个方式返回的原页面路由参数消失,此时使用$router.back(-1)返回原页面路由,参数仍存在。

go(-1) :原页面表单中的内容会丢失; this.$router.go(-1) :后退+刷新; this.$router.go(0) :刷新; this.$router.go(1) :前进;  history.go(-1) :后退+刷新; history.go(1) :前进;  back() :原页表表单中的内容会保留; this.$router.back() :后退 this.$router.back(0) 刷新 this.$router.back(1) 前进  history.back() 后退 history.back(0) 刷新 history.back(1) 前进

vue点击按钮跳转页面总结 router.push router.replace router.go

总结一下在Vue里面跳转页面的方法

首先是vue提供的router-link,使用后再页面里会转换为a标签

<router-link to="/test">go home</router-link>

使用函数进行任意页面跳转

普通跳转

<button @click="jump('/test')">Click Me</button> ? ?// 这里进行设置要跳转的路由
methods: {
? ? ? ? jump (path) {
? ? ? ? ? ? this.$router.replace(path)
? ? ? ? }
? ? ? ??
?? ??? ?// 或者
?? ??? ?jump (path) {
? ? ? ? ? ? this.$router.push({path: path})
? ? ? ? }
? ? }

带参数跳转

<button @click="jump('/test')">Click Me</button> ? ?// 这里进行设置要跳转的路由
methods: {
?? ??? ?jump (path) {
? ? ? ? ? ? this.$router.push({path: `${path}?a=1`})
? ? ? ? }
? ? ? ??
? ? ? ? // 或者
? ? ? ? jump (path) {
? ? ? ? ? ? this.$router.push({path: path, query:{a:123}})
? ? ? ? }
? ? }

前进

@click="$router.go(1)"

后退

@click="$router.back()"
?? ?// 或者
@click="$router.go(-1)"

刷新当前页面

@click="$router.go(0)"
?? ?// 或者
window.location.reload()
?? ?// 或者
history.go(0)

解析router.push 和 router.replace的区别 

先说结论: router.push会在浏览器历史纪录里面添加一条记录,router.replace不会在浏览器的历史记录里面添加信息。也就是通过router.push跳转的页面能够返回上一页。这里的上一页指的是跳转之前的那一页

验证:首先打开一个新的vue项目,把鼠标指针放在浏览器左上角的回退按钮并按住左键,能够看到目前浏览器历史记录除了默认新开打的一个页面没有任何其他vue路由信息

使用 this.$router.replace(path)这个方法跳转后,再次点击,可以看到路由跳转后,历史纪录里面跟新打开的项目一样。

说明使用router.replace不会往浏览器历史记录里添加信息。并且点击返回按钮也是返回到空页面,并不会返回到vue的首页

然后使用this.$router.push(path)方法,点击跳转后能够看到历史记录里面多了一条记录

点击返回后,也能够返回到首页。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

查看更多关于vue中$router.back()和$router.go()的用法的详细内容...

  阅读:28次