LoginSignup
0
0

More than 5 years have passed since last update.

ステップバイステップでLightningコンポーネントを楽しもう! - モジュール6

Last updated at Posted at 2015-09-03

データの一覧を表示してみよう

ApexからLeadデータの一覧を取得し画面に表示します。

画面イメージ

ソース

Apex

LeadController.cls
public class LeadController {

    @AuraEnabled
    public static List<Lead> findAll() {
        return [SELECT Id, LastName, Company FROM Lead ORDER BY LastModifiedDate DESC LIMIT 50];
    }

}

Component

m06_CallApex.cmp
<!-- controller属性でApexコントローラを指定 -->
<aura:component controller="LeadController" implements="force:appHostable">

    <!-- Leadオブジェクトの配列を属性にもつ -->
    <aura:attribute name="leads" type="Lead[]"/>

    <!-- 表示ライフサイクル中に発火されるinitイベント購読 -->
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <h3>リード表示</h3>

    <ul>
        <aura:iteration items="{!v.leads}" var="lead">
            <li>
                <p>
                    {!lead.Company}<br/>
                    {!lead.LastName}
                </p>
            </li>
        </aura:iteration>
    </ul>
</aura:component>
m06_CallApexController.js
({
    // initイベント処理
    doInit: function(component, event, helper) {
        // Apexコントローラのアクションを取得
        var action = component.get("c.findAll");
        // Apexコントローラ処理後のコールバック設定
        action.setCallback(this, function(a){
            component.set("v.leads", a.getReturnValue());
        });
        // 実行アクションキューに追加
        $A.enqueueAction(action);
    }
})

ポイント

Apex

コンポーネントからコールするApexでは以下が必要です。

  • @AuraEnabledアノテーション
  • Staticメソッド

コンポーネント

componentタグにApexコントローラを指定する属性(controller="LeadController") の追加が必要です。

コンポーネントコントローラ

  • c.<Apexメソッド名>でアクションを取得します。
  • setCallbackでコールバックの指定が可能です。
  • $AはJavaScriptでのAuraオブジェクトの短縮名です。
  • enqueueActionでは、個々のアクションごとにApexに送信するのではなく、イベントチェーンを処理し、関連する要求をバッチにまとめてからキューのアクションを実行します。

注意点

Apexコントローラとコンポーネントコントローラのメソッド名が重複するとエラーになります。

表示ライフサイクルイベント

  • init: コンポーネント初期化が完了した
  • render: コンポーネント表示開始
  • afterRender: コンポーネント表示完了
  • waiting: サーバ要求が実行された場合
  • doneWaiting: サーバ要求への応答待機終了
  • doneRendering: 再表示が必要なコンポーネントの再表示が終了

aura:iterationタグ

繰り返し処理が行えます。

補足

  • P132 表示ライフサイクル中に起動されたイベント
  • P173 コンポーネントの初期化時のアクション呼び出し
  • P182 Apexの使用
  • P188 サーバ側のアクションのコール
  • P217 aura:iteration

:arrow_backward: モジュール5へ | モジュール7へ :arrow_forward:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0