首页 > 解决方案 > 是否可以在离子侧边栏中使用幻灯片

问题描述

我正在用 ionic 构建一个移动应用程序,我想通过放置幻灯片来制作一个类似松弛的侧面菜单。

例如,当您单击主菜单项时,它会像 slack 一样滑出侧面菜单中的另一张幻灯片。

我尝试在离子菜单中使用离子幻灯片,但幻灯片不起作用。

请查看屏幕截图。

在此处输入图像描述

这是代码片段。

<ion-menu [content]="mycontent" [swipeEnabled]="false">
    <ion-content>

      <ion-slides>
        <ion-slide>
          <h1>Slide 1</h1>
        </ion-slide>
        <ion-slide>
          <h1>Slide 2</h1>
        </ion-slide>
        <ion-slide>
          <h1>Slide 3</h1>
        </ion-slide>
      </ion-slides>

  </ion-content>

</ion-menu>

<ion-nav #mycontent [root]="rootPage"></ion-nav>

这是我正在尝试构建的。

在此处输入图像描述

关于如何实现这一点的任何想法?

谢谢。

标签: ionic-frameworkionic3ion-slides

解决方案


ion-slides 组件在底层使用了 Swiper 库。Swiper 的部分初始化代码取决于知道幻灯片容器的宽度,以及clientWidth用于获取它的代码。由于菜单以 开头display:none,因此检索到的宽度始终为零,并且初始化代码会交给您。

您可以通过display:block在 Swiper 初始化时临时设置来解决此问题。我在组件内有我的侧边菜单,因此您可能需要根据您的情况调整此代码:

应用程序.html:

<sidebar [content]="content"></sidebar>
<ion-nav #content [root]="rootPage" swipeBackEnabled="false"></ion-nav>

边栏.html:

<ion-menu [content]="content" swipeEnabled="false">
  <ion-content>
    <ion-slides pager>
      <ion-slide>
        <h2>Slide 1</h2>
      </ion-slide>
      <ion-slide>
        <h2>Slide 2</h2>
      </ion-slide>
      <ion-slide>
        <h2>Slide 3</h2>
      </ion-slide>
    </ion-slides>
  </ion-content>
</ion-menu>

sidebar.component.ts:

...
@Component({
  selector: 'sidebar',
  templateUrl: 'sidebar.html',
})
export class SidebarComponent implements AfterViewInit {
  @Input('content') content: NavController;

  @ViewChild(Slides) slides: Slides;
  @ViewChild(Menu, { read: ElementRef }) menuRef: ElementRef;

  // Use Renderer2 instead of direct DOM manipulation through the
  // ElementRef.nativeElement.
  //
  // @see: https://medium.com/@kmathy/angular-manipulate-properly-the-dom-with-renderer-16a756508cba
  //
  constructor(private renderer: Renderer2) {
  }

  // ViewChild template references might not be available until
  // AfterViewInit lifecycle hook runs.
  //
  // @see: https://blog.angular-university.io/angular-viewchild/
  //
  ngAfterViewInit() {
    this.renderer.setStyle(this.menuRef.nativeElement, 'display', 'block');
    setTimeout(() => {
      // Swiper init has its own ngAfterViewInit code that delays 300ms
      // before running. Don't remove the 'display' style until after that.
      this.renderer.removeStyle(this.menuRef.nativeElement, 'display');
    }, 310);
  }

}

推荐阅读