Bài 43: Routing Tìm hiểu về ion-router, ion-router-link, ion-router-outlet, ion-route, ion-route-redirect

Bài 43: Routing Tìm hiểu về ion-router, ion-router-link, ion-router-outlet, ion-route, ion-route-redirect

 


ion-router

Bộ định tuyến(router) là một thành phần để xử lý định tuyến bên trong các dự án JavaScript vani và Stencil.

Lưu ý: thành phần này chỉ nên được sử dụng với các dự án JavaScript vani và Stencil. Đối với các dự án Angular, hãy sử dụng ion-router-outlet và bộ định tuyến Angular.

Các ứng dụng phải có một ion-router thành phần duy nhất trong cơ sở mã. Thành phần này kiểm soát tất cả các tương tác với lịch sử trình duyệt và nó tổng hợp các cập nhật thông qua một hệ thống sự kiện.

ion-router chỉ là một điều phối viên URL cho các cửa hàng điều hướng của ionic: ion-navvà ion-tabs.

Điều đó có nghĩa là ion-router không bao giờ chạm vào DOM, nó không hiển thị các thành phần hoặc phát ra bất kỳ loại sự kiện vòng đời, nó chỉ nói ion-navvà ion-tabsnhững gì và khi nào thì "hiển thị" dựa trên URL của trình duyệt.

Để định cấu hình mối quan hệ này giữa các thành phần (để tải / chọn) và URL, hãy ion-routersử dụng cú pháp khai báo bằng JSX / HTML để xác định một cây các tuyến.

 Usage

<ion-router>
  <ion-route component="page-tabs">
    <ion-route url="/schedule" component="tab-schedule">
      <ion-route component="page-schedule"></ion-route>
      <ion-route url="/session/:sessionId" component="page-session"></ion-route>
    </ion-route>

    <ion-route url="/speakers" component="tab-speaker">
      <ion-route component="page-speaker-list"></ion-route>
      <ion-route url="/session/:sessionId" component="page-session"></ion-route>
      <ion-route url="/:speakerId" component="page-speaker-detail"></ion-route>
    </ion-route>

    <ion-route url="/map" component="page-map"></ion-route>
    <ion-route url="/about" component="page-about"></ion-route>
  </ion-route>

  <ion-route url="/tutorial" component="page-tutorial"></ion-route>
  <ion-route url="/login" component="page-login"></ion-route>
  <ion-route url="/account" component="page-account"></ion-route>
  <ion-route url="/signup" component="page-signup"></ion-route>
  <ion-route url="/support" component="page-support"></ion-route>
</ion-router>

Properties

root

Description

By default ion-router will match the routes at the root path ("/"). That can be changed when

Attributeroot
Typestring
Default'/'

useHash

Description

The router can work in two "modes":

  • With hash: /index.html#/path/to/page
  • Without hash: /path/to/page

Using one or another might depend in the requirements of your app and/or where it's deployed.

Usually "hash-less" navigation works better for SEO and it's more user friendly too, but it might requires additional server-side configuration in order to properly work.

On the otherside hash-navigation is much easier to deploy, it even works over the file protocol.

By default, this property is true, change to false to allow hash-less URLs.

Attributeuse-hash
Typeboolean
Defaulttrue

Events

NameDescription
ionRouteDidChangeEmitted when the route had changed
ionRouteWillChangeEvent emitted when the route is about to change

Methods

back

Description

Go back to previous page in the window.history.

Signatureback() => Promise<void>

push

Description

Navigate to the specified URL.

Signaturepush(url: string, direction?: RouterDirection, animation?: AnimationBuilder | undefined) => Promise<boolean>

ion-router-link

router link component được sử dụng để điều hướng đến một liên kết được chỉ định. Tương tự như thẻ liên kết của trình duyệt, nó có thể chấp nhận một href cho vị trí và một hướng cho hoạt ảnh chuyển tiếp.

Lưu ý: thành phần này chỉ nên được sử dụng với các dự án JavaScript vani và Stencil. Đối với các dự án Angular, hãy sử dụng <a>và routerLinkvới bộ định tuyến Angular.

 



Properties

color

Description

The color to use from your application's color palette. Default options are: "primary""secondary""tertiary""success""warning""danger""light""medium", and "dark". For more information on colors, see theming.

Attributecolor
Typestring | undefined

href

Description

Contains a URL or a URL fragment that the hyperlink points to. If this property is set, an anchor tag will be rendered.

Attributehref
Typestring | undefined

rel

Description

Specifies the relationship of the target object to the link object. The value is a space-separated list of link types.

Attributerel
Typestring | undefined

routerAnimation

Description

When using a router, it specifies the transition animation when navigating to another page using href.

Type((baseEl: any, opts?: any) => Animation) | undefined

routerDirection

Description

When using a router, it specifies the transition direction when navigating to another page using href.

Attributerouter-direction
Type"back" | "forward" | "root"
Default'forward'

target

Description

Specifies where to display the linked URL. Only applies when an href is provided. Special keywords: "_blank""_self""_parent""_top".

Attributetarget
Typestring | undefined

CSS Custom properties

NameDescription
--backgroundBackground of the router link
--colorText color of the router link

ion-router-outlet

Router outlet là một thành phần được sử dụng để định tuyến trong ứng dụng Angular hoặc Vue. Nó hoạt động theo cách tương tự như thành phần router outlet tích hợp của Angular và thành phần chế độ xem router của Vue, nhưng chứa logic để cung cấp điều hướng xếp chồng và các chế độ xem hoạt hình vào và ra.

Lưu ý: thành phần này chỉ nên được sử dụng với các dự án Angular và Vue. Đối với các dự án JavaScript vani hoặc Stencil, hãy sử dụngion-router và ion-route.

Mặc dù router outlet có các phương pháp điều hướng xung quanh, nhưng bạn nên sử dụng các phương pháp điều hướng trong router outlet của khung công tác của mình.

 Life Cycle Hooks

Routes rendered được hiển thị trong Router Outlet có quyền truy cập vào các sự kiện Ionic cụ thể được kết nối với hình ảnh động

Event NameTrigger
ionViewWillEnterFired when the component routing to is about to animate into view.
ionViewDidEnterFired when the component routing to has finished animating.
ionViewWillLeaveFired when the component routing from is about to animate.
ionViewDidLeaveFired when the component routing to has finished animating.

Các sự kiện này liên kết với hệ thống hoạt ảnh của Ionic và có thể được sử dụng để điều phối các phần của ứng dụng của bạn khi một Thành phần được thực hiện với hoạt ảnh của nó. Những sự kiện này không phải là sự thay thế cho hệ thống sự kiện của riêng khuôn khổ của bạn, mà là một sự bổ sung.

Để xử lý các Bộ định tuyến bảo vệ, cũ hơn ionViewCanEntervà ionViewCanLeaveđã được thay thế bằng khung cụ thể tương đương của chúng. Đối với Angular, 

 Properties


animated

Description

If true, the router-outlet should animate the transition of components.

Attributeanimated
Typeboolean
Defaulttrue

animation

Description

By default ion-nav animates transition between pages based in the mode (ios or material design). However, this property allows to create custom transition using AnimateBuilder functions.

Type((baseEl: any, opts?: any) => Animation) | undefined

mode

Description

The mode determines which platform styles to use.

Attributemode
Type"ios" | "md"
DefaultgetIonMode(this)

ion-route


interfaces

  interface NavigationHookOptions {
    /**
     * A valid path to redirect navigation to.
     */
    redirectstring;
  }

Usage

<ion-router>
  <ion-route url="/home" component="page-home"></ion-route>
  <ion-route url="/dashboard" component="page-dashboard"></ion-route>
  <ion-route url="/new-message" component="page-new-message"></ion-route>
  <ion-route url="/login" component="page-login"></ion-route>
</ion-router>
CopyCopied
const dashboardPage = document.querySelector('ion-route[url="/dashboard"]');
dashboardPage.beforeEnter = isLoggedInGuard;

const newMessagePage = document.querySelector('ion-route[url="/dashboard"]');
newMessagePage.beforeLeave = hasUnsavedDataGuard;

const isLoggedInGuard = async () => {
  const isLoggedIn = await UserData.isLoggedIn(); // Replace this with actual login validation

  if (isLoggedIn) {
    return true;
  } else {
    return { redirect: '/login' }; // If a user is not logged in, they will be redirected to the /login page
  }
}

const hasUnsavedDataGuard = async () => {
  const hasUnsavedData = await checkData(); // Replace this with actual validation

  if (hasUnsavedData) {
    return await confirmDiscardChanges();
  } else {
    return true;
  }
}

const confirmDiscardChanges = async () => {
  const alert = document.createElement('ion-alert');
  alert.header = 'Discard Unsaved Changes?';
  alert.message = 'Are you sure you want to leave? Any unsaved changed will be lost.';
  alert.buttons = [
    {
      text: 'Cancel',
      role: 'Cancel',
    },
    {
      text: 'Discard',
      role: 'destructive',
    }
  ];

  document.body.appendChild(alert);

  await alert.present();

  const { role } = await alert.onDidDismiss();

  return (role === 'Cancel') ? false : true;
}
import { Component, h } from '@stencil/core';
import { alertController } from '@ionic/core';

@Component({
  tag: 'router-example',
  styleUrl: 'router-example.css'
})
export class RouterExample {
  render() {
    return (
      <ion-router>
        <ion-route url="/home" component="page-home"></ion-route>
        <ion-route url="/dashboard" component="page-dashboard" beforeEnter={isLoggedInGuard}></ion-route>
        <ion-route url="/new-message" component="page-new-message" beforeLeave={hasUnsavedDataGuard}></ion-route>
        <ion-route url="/login" component="page-login"></ion-route>
      </ion-router>
    )
  }
}

const isLoggedInGuard = async () => {
  const isLoggedIn = await UserData.isLoggedIn(); // Replace this with actual login validation

  if (isLoggedIn) {
    return true;
  } else {
    return { redirect: '/login' }; // If a user is not logged in, they will be redirected to the /login page
  }
}

const hasUnsavedDataGuard = async () => {
  const hasUnsavedData = await checkData(); // Replace this with actual validation

  if (hasUnsavedData) {
    return await confirmDiscardChanges();
  } else {
    return true;
  }
}

const confirmDiscardChanges = async () => {
  const alert = await alertController.create({
    header: 'Discard Unsaved Changes?',
    message: 'Are you sure you want to leave? Any unsaved changed will be lost.',
    buttons: [
      {
        text: 'Cancel',
        role: 'Cancel',
      },
      {
        text: 'Discard',
        role: 'destructive',
      }
    ]
  });

  await alert.present();

  const { role } = await alert.onDidDismiss();

  return (role === 'Cancel') ? false : true;
}
<template>
  <ion-router>
    <ion-route url="/home" component="page-home"></ion-route>
    <ion-route url="/dashboard" component="page-dashboard" :beforeEnter="isLoggedInGuard"></ion-route>
    <ion-route url="/new-message" component="page-new-message" :beforeLeave="hasUnsavedDataGuard"></ion-route>
    <ion-route url="/login" component="page-login"></ion-route>
  </ion-router>
</template>

<script>
  import { alertController } from '@ionic/vue';

  const isLoggedInGuard = async () => {
    const isLoggedIn = await UserData.isLoggedIn(); // Replace this with actual login validation

    if (isLoggedIn) {
      return true;
    } else {
      return { redirect: '/login' }; // If a user is not logged in, they will be redirected to the /login page
    }
  }

  const hasUnsavedDataGuard = async () => {
    const hasUnsavedData = await checkData(); // Replace this with actual validation

    if (hasUnsavedData) {
      return await confirmDiscardChanges();
    } else {
      return true;
    }
  }

  const confirmDiscardChanges = async () => {
    const alert = await alertController.create({
      header: 'Discard Unsaved Changes?',
      message: 'Are you sure you want to leave? Any unsaved changed will be lost.',
      buttons: [
        {
          text: 'Cancel',
          role: 'Cancel',
        },
        {
          text: 'Discard',
          role: 'destructive',
        }
      ]
    });

    await alert.present();

    const { role } = await alert.onDidDismiss();

    return (role === 'Cancel') ? false : true;
  }
</script>

Properties

beforeEnter

Description

A navigation hook that is fired when the route tries to enter. Returning true allows the navigation to proceed, while returning false causes it to be cancelled. Returning a NavigationHookOptions object causes the router to redirect to the path specified.

Type(() => NavigationHookResult | Promise<NavigationHookResult>) | undefined

beforeLeave

Description

A navigation hook that is fired when the route tries to leave. Returning true allows the navigation to proceed, while returning false causes it to be cancelled. Returning a NavigationHookOptions object causes the router to redirect to the path specified.

Type(() => NavigationHookResult | Promise<NavigationHookResult>) | undefined

component

Description

Name of the component to load/select in the navigation outlet (ion-tabsion-nav) when the route matches.

The value of this property is not always the tagname of the component to load, in ion-tabs it actually refers to the name of the ion-tab to select.

Attributecomponent
Typestring

componentProps

Description

A key value { 'red': true, 'blue': 'white'} containing props that should be passed to the defined component when rendered.

Typeundefined | { [key: string]: any; }

url

Description

Relative path that needs to match in order for this route to apply.

Accepts paths similar to expressjs so that you can define parameters in the url /foo/:bar where bar would be available in incoming props.

Attributeurl
Typestring
Default''

Events

NameDescription
ionRouteDataChangedUsed internally by `ion-router` to know when this route did change.

 ion-route-redirect

Chỉ có thể sử dụng route redirect với ion-routertư cách là con trực tiếp của nó.

Lưu ý: thành phần này chỉ nên được sử dụng với các dự án JavaScript vani và Stencil. Đối với các dự án Angular, hãy sử dụngion-router-outlet và bộ định tuyến Angular.

Chuyển hướng route redirect có hai thuộc tính có thể định cấu hình:

from

to

Nó chuyển hướng "từ" một URL "sang" một URL khác. Khi quy tắc ion-route-redirect đã xác định khớp, bộ định tuyến sẽ chuyển hướng từ đường dẫn được chỉ định trong thuộc fromtính đến đường dẫn trong thuộc totính. Để chuyển hướng xảy ra, fromđường dẫn cần phải khớp chính xác với URL được điều hướng.

 Multiple route Redirects

Một số lượng tùy ý các tuyến chuyển hướng có thể được xác định bên trong một ion-router, nhưng chỉ một tuyến có thể phù hợp.

Một chuyển hướng tuyến sẽ không bao giờ gọi một chuyển hướng khác sau chuyển hướng của chính nó, vì điều này có thể dẫn đến các vòng lặp vô hạn.

Thực hiện hai chuyển hướng sau:

  <ion-router>
  <ion-route-redirect from="/admin" to="/login"></ion-route-redirect>
  <ion-route-redirect from="/login" to="/admin"></ion-route-redirect>
</ion-router>

Nếu người dùng điều hướng đến /adminbộ định tuyến sẽ chuyển hướng đến /loginvà dừng lại ở đó. Nó sẽ không bao giờ đánh giá nhiều hơn một chuyển hướng.

Usage

<!-- Redirects when the user navigates to `/admin` but
will NOT redirect if the user navigates to `/admin/posts` -->
<ion-route-redirect from="/admin" to="/login"></ion-route-redirect>

<!-- By adding the wilcard character (*), the redirect will match
any subpath of admin -->
<ion-route-redirect from="/admin/*" to="/login"></ion-route-redirect>

Route Redirects as Guards

Redirection routes có thể hoạt động như những người bảo vệ để ngăn người dùng điều hướng đến các khu vực nhất định của ứng dụng dựa trên một điều kiện nhất định, chẳng hạn như liệu người dùng có được xác thực hay không.

Redirection routes có thể được thêm và xóa động để chuyển hướng (hoặc bảo vệ) một số tuyến đường không bị truy cập. Trong ví dụ sau, tất cả các url *sẽ được chuyển hướng đến /loginurl nếu isLoggedIncó false.

  const isLoggedIn = false;

  const router = document.querySelector('ion-router');
  const routeRedirect = document.createElement('ion-route-redirect');
  routeRedirect.setAttribute('from''*');
  routeRedirect.setAttribute('to''/login');
  
  if (!isLoggedIn) {
    router.appendChild(routeRedirect);
  }

Ngoài ra, giá trị của to có thể được sửa đổi dựa trên một điều kiện. Trong ví dụ sau, chuyển hướng tuyến sẽ kiểm tra xem người dùng đã đăng nhập hay chưa và chuyển hướng đến /login url nếu chưa.

  <ion-route-redirect id="tutorialRedirect" from="*"></ion-route-redirect>

  const isLoggedIn = false;
const routeRedirect = document.querySelector('#tutorialRedirect');

routeRedirect.setAttribute('to'isLoggedIn ? undefined : '/login');

Properties

from

Description

Một tuyến đường chuyển hướng, chuyển hướng "từ" một URL "đến" một URL khác. Thuộc tính này là URL "từ". Nó cần phải khớp chính xác với URL được điều hướng để áp dụng.

Đường dẫn được chỉ định trong giá trị này luôn là đường dẫn tuyệt đối, ngay cả khi /dấu gạch chéo đầu tiên không được chỉ định.

Attributefrom
Typestring

to

Description

Một tuyến đường chuyển hướng, chuyển hướng "từ" một URL "đến" một URL khác. Thuộc tính này là URL "tới" đó. Khi quy ion-route-redirecttắc đã xác định khớp, bộ định tuyến sẽ chuyển hướng đến đường dẫn được chỉ định trong thuộc tính này.

Giá trị của thuộc tính này luôn là một đường dẫn tuyệt đối bên trong phạm vi các tuyến đường được xác định trong ion-routernó không thể được sử dụng với một bộ định tuyến khác hoặc để thực hiện chuyển hướng đến một miền khác.

Lưu ý rằng đây là chuyển hướng ảo, nó sẽ không gây ra làm mới trình duyệt thực, một lần nữa, đó là chuyển hướng bên trong ngữ cảnh của ion-router.

Khi thuộc tính này không được chỉ định hoặc giá trị của thuộc tính này là undefinedtoàn bộ tuyến đường chuyển hướng không hoạt động, ngay cả khi giá trị "from" khớp.

Attributeto
Typenull | string | undefined

Events

NameDescription
ionRouteRedirectChangedSự kiện nội bộ kích hoạt khi bất kỳ giá trị nào của quy tắc này được thêm / xóa khỏi DOM hoặc bất kỳ thuộc tính công khai nào của anh ta thay đổi. `ion-router` ghi lại sự kiện này để cập nhật sổ đăng ký nội bộ của mình về các quy tắc bộ định tuyến.

Đăng nhận xét

0 Nhận xét

myadcash