Ionic 【tabs模板】 详情页刷新以后,页面数据不消失,点击返回按钮可回到首页

1.详情页刷新,确保当前页面数据不丢失

  • 首先假设 首页(home)跳转到 home-details,传递参数code:
    //home.ts
    this.navCtrl.push(HomeDetailsPage,{
      code:code
    })
  • 然后再home-details.ts中获取传过来的参数:
    //home-details.ts
    this.id = this.navParams.get('code');
  • 最后,设置地址栏的形式:
    //home-details.ts
    @IonicPage({
      name: 'HomeDetailsPage',
      segment: 'details/:code'
    })

2.页面刷新以后返回按钮会消失,此处你可以让返回按钮,强制显示,也可以自行添加一个返回按钮

  • 自行添加一个返回按钮
    //home.details.html
    <ion-icon name="arrow-back" class="violet back-icon" (click)="back()"></ion-icon>

3.点击返回按钮,回到TabsPage页面

  • //home.details.ts
    back(){
    //注意,setRoot(),括号内不能直接填写HomePage,否则,tabs会消失
     this.app.getRootNav().setRoot(TabsPage);  
    }

    注意:此时回到首页以后,发现地址栏url并没有变化,此时点击刷新以后,页面仍然显示的是详情页

  • //home.details.ts
    @IonicPage({
      name: 'HomeDetailsPage',
      segment: 'details/:code'
    })
    
    ========================================================================
    
     back() {
    
    //首次进入详情页地址栏:http://localhost:8100/#/home/details/code
    //当详情页刷新以后地址栏:http://localhost:8100/#/details/code
    
     location.href.indexOf('#/details');   //这里判断页面是否刷新,如果刷新回退2级,否则退到上一级
    
        this.UrlCompare = (location.href.indexOf('#/details') > 0) ? -2 : -1
    
         this.app.getRootNav().setRoot(TabsPage, {  //跳转回到TabsPage,并且传参数
          item: 'home',
          UrlCompare:this.UrlCompare
        });
    
      }

4.在TabsPage页面,根据传回的参数,判断url应该回退几次,以及该显示在哪一个tabs页面

  •      
    //定义变量
     item: string;
     UrlCompare: number;
    
     constructor(public navCtrl: NavController, public navParams: NavParams) {
    
        this.item = this.navParams.get('item');
        this.UrlCompare = this.navParams.get('UrlCompare');
       //根据值,判断回退几次
        if(this.UrlCompare !=null ||this.UrlCompare !=undefined){
          window.history.go(this.UrlCompare);
        } 
      }
    
      ionViewDidEnter() {
    
        if (this.item != undefined) {
           //根绝不同的参数进入不同的页面
          if (this.item == 'home') {
            this.tabRef.select(0);
          } else if (this.item == 'user') {
            this.tabRef.select(1);
          }
    
        }
    
      }

PS:默认.隐藏全部子页面tabs

  • 在app.module.ts里配置
  •  
     IonicModule.forRoot(MyApp, {
          tabsHideOnSubPages: 'true', //隐藏全部子页面tabs
      })

猜你喜欢

转载自blog.csdn.net/qq_37201926/article/details/83894857