当前位置: 首页 > Web前端 > HTML5

在angular中制作自己的页面栈

时间:2023-04-05 22:08:25 HTML5

项目,需要开发一个类似微信底部的打开网页时的前进后退按钮组件。可以根据路由在栈中的位置判断按钮是前进还是后退,并改变按钮对应的颜色,这需要您自己创建一个页面堆栈。思路是通过HTML5的history.length属性知道浏览器页面历史中存在的页面数量,同时监听angualr的router获取当前页面的路由添加到自己的页面中堆。1、每次进入一个页面,首先判断页面栈中??是否存在该路由,不存在则压入。2、当栈中的路由数量超过浏览器历史栈长度时,删除多余的页面,从而保证自己的页面栈和浏览器的页面栈始终一致。3、获取当前路由在页面栈中的位置,通过索引和栈长改变页面元素的样式。详细实现过程如下:import{Component,OnInit}from'@angular/core';从'@angular/router'导入{Router,NavigationEnd};@Component({selector:'app-foot',templateUrl:'./foot.component.html',styleUrls:['./foot.component.scss']})exportclassFootComponentimplementsOnInit{routerArr=[];//页面栈routerPath='';//当前路线idx=0;//当前路由索引构造函数(privateroute:Router){//打开应用时,如果判断历史栈长度为1,则清除缓存中的页面栈if(history.length==1){localStorage.removeItem("routerArr");}让storageRouter=JSON.parse(localStorage.getItem("routerArr"));存储路由器?this.routerArr=storageRouter:'';//监听页面路由变化this.route.events.subscribe((data)=>{//路由导航结束后if(datainstanceofNavigationEnd){//当前页面路由this.routerPath=data.url.substr(1);if(this.routerPath==""){this.routerPath="home";}//添加一个新路由到页面栈中if(!this.routerArr.includes(this.router路径)){this.routerArr.push(this.routerPath);//如果页面堆栈长度超过浏览器历史堆栈长度,删除历史长度前一位和新页面之间的页面if(this.routerArr.length>history.length){this.routerArr.splice(history.length-1,this.routerArr.length-history.length);}}//当前路由在页面栈中的索引this.idx=this.routerArr.indexOf(this.routerPath)+1;localStorage.setItem("routerArr",JSON.stringify(this.routerArr));}})}ngOnInit(){}//返回goBack(){history.go(-1);}//前进goAhead(){history.go(1);}}