Vue里点击按钮跳转页面总结,router.push router.replacerouter.go

mac2022-06-30  31

总结一下在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)方法,点击跳转后能够看到历史记录里面多了一条记录 点击返回后,也能够返回到首页。

最新回复(0)