ionic 自动下拉刷新

1,141 阅读1分钟

ionic 自动下拉刷新

通过程序的方式,实现 ion-refresher 下拉刷新

效果预览

基本

在页面添加 ion-refresher 组件

<ion-content>
  <ion-refresher (ionRefresh)="doRefresh($event)">
    <ion-refresher-content></ion-refresher-content>
  </ion-refresher>

  <button ion-button (click)="startRefresh()">刷新</button>
</ion-content>

编写触发下拉方法

import { ViewChild } from '@angular/core';
import { Refresher, Content } from 'ionic-angular';

export class MyPage {
  @ViewChild(Content) content: Content;
  @ViewChild(Refresher) refresher: Refresher;

  constructor() {}

  startRefresh() {
    this.refresher._top = `${this.content.contentTop}px`;
    this.refresher.state = 'refreshing';
    this.refresher._beginRefresh();
  }

  doRefresh(refresher: Refresher) {
    /*
      // 一些异步操作
      refresher.complete();
    */

    // Example
    setTimeout(() => {
      refresher.complete();
    }, 2000);
  }
}

进页面后立即下拉获取数据

类似微博的效果,进入页面之后,下拉获取数据

import { ViewChild } from '@angular/core';
import { Refresher, Content } from 'ionic-angular';

export class MyPage {
  @ViewChild(Content) content: Content;
  @ViewChild(Refresher) refresher: Refresher;

  constructor() {}

  ionViewDidLoad() {
    
    this.waitContentTop()
    .then(() => {
      this.startRefresh();
    });
    
  }

  // 等待ContentTop
  waitContentTop(): Promise<number> {
    return new Promise((resolve, reject) => {
      const timer = setInterval(() => {
        if (this.content.contentTop) {
          resolve(this.content.contentTop);
          clearInterval(timer);
        }
      }, 0);
    });
  }

  startRefresh() {
    this.refresher._top = `${this.content.contentTop}px`;
    this.refresher.state = 'refreshing';
    this.refresher._beginRefresh();
  }

  doRefresh(refresher: Refresher) {
    /*
      // 一些异步操作
      refresher.complete();
    */

    // Example
    setTimeout(() => {
      refresher.complete();
    }, 2000);
  }
}