为什么要清除路由历史记录

1、在公众号H5的开发(使用vue + vant)中,我不想往路由增加历史记录。
2、从A页面→B页面→C页面,直接返回A页面

路由跳转

push

router.push(location, onComplete?, onAbort?)

声明式编程式
<router-link :to="...">router.push(...)

1、this.$router.push("/HomePage");this.$router.push({ path: "/HomePage" });向 history 栈增加一条记录
2、this.$router.push({ path: "/HomePage", replace: true });并不增加 history 记录而是替换当前的 history 记录

replace

router.replace(location, onComplete?, onAbort?)

声明式编程式
<router-link :to="..." replace>router.replace(...)

1、this.$router.replace({ path: "/HomePage" });并不增加 history 记录而是替换当前的 history 记录

清除路由历史记录

1、A页面→B页面,回到A页面。相当于返回上一页this.$router.go(-1);
2、A页面→B页面→C页面,回到A页面,再点返回键不会回到A、B、C这些页面。实际项目中这种情况出现的比较多。
对于知道层数的我们可以使用router.go(n),即

this.$router.go(-2);

我们可以使用这种方法返回到 history 栈中的指定页面(已知页面,知道回到那个页面需要点返回键的次数)

像不知道多少层的我们可以像下面这样,可用于在较深的页面回到首页

let backlen = window.history.length - 1;
window.history.go(-backlen);
this.$router.replace({ path: '/HomePage' });

3、A页面→B页面→C页面,点返回键到A页面。
在B页面→C页面的时候使用this.$router.replace({ path: C页面路由 });这个时候相当于 history 栈上之后A页面和C页面,A页面就是C页面的上一个页面,所以就实现了点返回键回到A页面

我们也可以用原生的方法来替换,实现同等效果
window.location.href = "http://localhost:8080/HomePage";增加 history 记录
window.location.replace("http://localhost:8080/HomePage");替换 history 记录
window.history.go(-1);返回上一页

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐