vue 路由嵌入iframe 刷新保留当前页面
项目场景:
我们有时候在页面中嵌套iframe,但是点击浏览器的刷新按钮的时候,页面会回到初始路径的页面,不会在当前页面刷新,这就很烦躁
解决方案:
mounted() {
window.addEventListener('beforeunload', e => {
sessionStorage.setItem('beforeunload', 1);
});
// 监听页面刷新
if(sessionStorage.getItem('beforeunload') == 1){
let name = sessionStorage.getItem("routerName");
if (name) {
this.$nextTick(function() {
this.$router.push({ path: name });
});
}
}
},
watch: {
$route: function (oldroute) {
if (oldroute.path == "/login") {
this.show = false;
} else {
this.show = true;
}
if(oldroute.name == null){
sessionStorage.removeItem('beforeunload');
}
},
},
2.每一个路由都要加上name,才可以对name进行判断
router.beforeEach((to, from, next) => {
if (from.name != null)
sessionStorage.setItem("routerName", to.fullPath);
next();
});
最终,当前vue项目的iframe对应刷新的时候,路由保持当前页面,当外层vue项目tab切换的时候,路由又会重置到最原始的嵌入页面。