vue返回首页后如何清空路由问题
作者:ジ Jing
这篇文章主要介绍了vue返回首页后如何清空路由问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
vue返回首页后如何清空路由
需求一:从首页点击路由到A页面
- A页面点击路由到B页面
- B页面点击路由到C页面
- C页面点击路由链接到D页面
- D页面有个返回首页按钮
那么问题来了
点击返回首页后,再点击手机的返回键 会打开D页面 再按手机返回键 会打开C页面,依次类推,
如何才能实现点击返回首页后,清空路由呢
mounted () {
if (window.history && window.history.pushState) {
// 向历史记录中插入了当前页
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.goBack, false);
}
},
destroyed () {
window.removeEventListener('popstate', this.goBack, false);
},
methods: {
goBack () {
// console.log("点击了浏览器的返回按钮");
sessionStorage.clear();
window.history.back();
},
} 禁止有返回记录
mounted () {
if (window.history && window.history.pushState) {
// 向历史记录中插入了当前页
history.pushState(null, null, document.URL);
window.addEventListener('popstate', this.goBack, false);
}
},
destroyed () {
window.removeEventListener('popstate', this.goBack, false);
},
methods: {
goBack () {
// console.log("点击了浏览器的返回按钮");
history.pushState(null, null, document.URL);
},
} 需求二:把浏览器的记录返回指定的页面
mounted 中:
if (window.history && window.history.pushState) {
history.pushState(null, null, document.URL);
window.addEventListener("popstate", _this.onClickLeft, false); //_this.onClickLeft是返回的点击事件
} methods: {
onClickLeft() {
// this.$route.query.radio支付页面到指定页面传的参数 来判断他的路由
if (this.$route.query.radio == 1 || this.$route.query.radio == 2) {
this.$router.push({ //返回指定页面
});
} else {
this.$router.go(-1); // 正常返回
}
},// 将事件清除掉
destroyed() {
window.removeEventListener("popstate", this.onClickLeft, false);
}vue路由缓存的灵活清空
vue的路由缓存,灵活清空,在页面离开时判断
beforeRouteLeave:function(to, from, next){
// 增加离开路由时清除keep-alive
//rank写在router.js的路由meta里面,用来判断rank信息,可自由更改
if (from && from.meta.rank && to.meta.rank && from.meta.rank == to.meta.rank)
{//此处判断是如果返回上一层,你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
if (this.$vnode && this.$vnode.data.keepAlive)
{
if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)
{
if (this.$vnode.componentOptions)
{
var key = this.$vnode.key == null
? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
: this.$vnode.key;
var cache = this.$vnode.parent.componentInstance.cache;
var keys = this.$vnode.parent.componentInstance.keys;
if (cache[key])
{
if (keys.length) {
var index = keys.indexOf(key);
if (index > -1) {
keys.splice(index, 1);
}
}
delete cache[key];
}
}
}
}
this.$destroy();
}
next();
},总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
