본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

ion-route

원문 보기 위키 갱신

ion-route 컴포넌트는 컴포넌트 하나를 받아, 브라우저 URL이 url 프로퍼티와 일치할 때 그 컴포넌트를 렌더링해 줘요.

출처: 문서

본문

ion-route 컴포넌트는 컴포넌트를 받아, 브라우저 URL이 url 프로퍼티와 일치할 때 그 컴포넌트를 렌더링합니다.

Note

참고: 이 컴포넌트는 vanilla와 Stencil JavaScript 프로젝트에서만 사용해야 해요. Angular 프로젝트에서는 ion-router-outlet과 Angular 라우터를 사용하세요.

내비게이션 훅은 작업을 수행하거나 내비게이션 가드(guard) 역할을 하는 데 사용할 수 있어요. 훅은 각 ion-route의 beforeEnter와 beforeLeave 프로퍼티에 함수를 제공하는 방식으로 사용됩니다. true를 반환하면 내비게이션이 진행되도록 허용하고, false를 반환하면 취소됩니다. NavigationHookOptions 타입의 객체를 반환하면 내비게이션을 다른 페이지로 리다이렉트할 수 있어요.

Interfaces

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

Usage

Javascript

<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>
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;
};

Stencil

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;
};

Vue

<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: 라우트가 진입하려 할 때 발생하는 내비게이션 훅이에요. true를 반환하면 내비게이션이 진행되도록 허용하고, false를 반환하면 취소됩니다. NavigationHookOptions 객체를 반환하면 라우터가 지정된 경로로 리다이렉트해요.

Attribute: undefined

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

Default: undefined

beforeLeave

Description: 라우트가 떠나려 할 때 발생하는 내비게이션 훅이에요. true를 반환하면 내비게이션이 진행되도록 허용하고, false를 반환하면 취소됩니다. NavigationHookOptions 객체를 반환하면 라우터가 지정된 경로로 리다이렉트해요.

Attribute: undefined

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

Default: undefined

component

Description: 라우트가 일치할 때 내비게이션 아울렛(ion-tabs, ion-router-outlet)에서 로드하거나 선택할 컴포넌트의 이름이에요. 이 프로퍼티의 값이 항상 로드할 컴포넌트의 태그 이름인 것은 아닙니다. ion-tabs에서는 실제로 선택할 ion-tab의 이름을 가리켜요.

Attribute: component

Type: string

Default: undefined

componentProps

Description: 렌더링될 때 정의된 컴포넌트에 전달해야 하는 프로퍼티를 담는 키-값 { 'red': true, 'blue': 'white'} 쌍이에요.

Attribute: undefined

Type: undefined | { [key: string]: any; }

Default: undefined

url

Description: 이 라우트가 적용되기 위해 일치해야 하는 상대 경로예요. expressjs와 비슷한 경로를 받아들여서 /foo/ :bar 처럼 url에 파라미터를 정의할 수 있고, 이 경우 bar는 들어오는 props에서 사용할 수 있습니다.

Attribute: url

Type: string

Default: ''

Events

Name Description Bubbles
ionRouteDataChanged 이 라우트가 변경되었는지 알기 위해 ion-router가 내부적으로 사용해요. true

Methods

이 컴포넌트에는 공개 메서드가 없어요.

CSS Shadow Parts

이 컴포넌트에는 사용할 수 있는 CSS shadow part가 없어요.

CSS Custom Properties

이 컴포넌트에는 사용할 수 있는 CSS 커스텀 프로퍼티가 없어요.

Slots

이 컴포넌트에는 사용할 수 있는 슬롯이 없어요.

더 알아보기 (Learn more)

ion-route는 URL과 컴포넌트를 연결해 라우팅하는 단위예요. 내비게이션 훅을 활용하면 로그인 여부 등 조건에 따라 접근을 제어하거나 리다이렉트할 수 있어요. 실제 라우팅 체계는 ion-router 문서를 함께 참고하세요.