1. 程式人生 > >salesforce lightning零基礎學習(十四) Toast 淺入淺出

salesforce lightning零基礎學習(十四) Toast 淺入淺出

本篇參考:

https://developer.salesforce.com/docs/component-library/bundle/force:showToast/specification

https://archive-2_9_4.lightningdesignsystem.com/components/toast/

Toast在專案中是基本不可能用不到的元件,用於在頁面頭部展示一條訊息。之前也經常的用,但是沒有深入的研究過,最近正好開始做lightning專案,便深入研究了一下,發現比以前瞭解的稍微多點,特此總結,便於以後的檢視以及給沒有接觸過的小夥伴掃個盲。

一. Toast

Toast 用於在頁面的頭部展示一條訊息,比如我們在更新資料完成後會提示修改成功,出現異常會提示更新失敗等。Lightning將Toast封裝成了事件,我們只需要根據指定的步驟獲取Toast事件並且進行fire觸發即可。下方的demo中展示了toast的使用,使用 $A.get("e.force:showToast")便可以獲取事件,新增相關的屬性觸發即可實現Toast功能。

showToast : function(component, event, helper) {
    var toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams({
        "title": "Success!",
        "message": "The record has been updated successfully."
    });
    toastEvent.fire();
}

那麼 Toast 有哪些引數呢?

  • title:此引數用於展示message的標題區域,通常標題會以稍微大的字型展示在上方;
  • duration:此引數用於設定當前的Toast展示多久後自動消失,單位為毫秒,此屬性可以不填寫,預設為5秒中,如果設定的時間不足5秒也會按照5秒處理;
  • message:此引數用於展示顯示Toast的內容;
  • mode:Toast展示的模式,Toast支援三種模式:dismissible(展示的訊息包含一個關閉按鈕,如果點選按鈕則可以馬上Toast消失,如果不點選則預設過5秒消失,這個是預設選項) / pester(不展示關閉按鈕,過幾秒以後自動消失) / sticky(只展示關閉按鈕,不點選關閉按鈕則永遠不消失)
  • type:Toast的型別,不同的型別會展示不同的圖示以及不同的顏色樣式。可選擇的值有: error / warning / success / info / other。 前四個我們可能經常用,最後一個不經常用,其實other是此屬性的預設值,展示的顏色樣式和info相同,區別是此種不展示圖示。當然不展示圖示不是絕對的,如果搭配了key屬性可以展示其他的圖示,所以如果我們想要展示info的樣式但是不想使用info的圖示,我們可以考慮使用other然後設定key即可。
  • key:當我們的type選擇了other的情況下,此處可以指定toast裡面展示的other圖示,名字可以在lightning design system的icon中選擇。
  • messageTemplate: 上面的message用於Toast的訊息展示,但是隻能展示String字串的資訊,如果我們需要其他增強的功能展示(比如想要在toast的message中展示一個可以點選的URL),我們需要使用messageTemplate通過placeholder放入形參,使用messageTemplateData進行填充。 messageTemplate的placeholder很像我們在custom label中宣告,也是從0開始,使用{}.比如Record {0} created! See it {1}這裡就設定了兩個placeholder,messageTemplateData需要傳兩個引數進來。
  • messageTemplateData:當時用了messageTemplate以後,需要使用此屬性去將placeholder的值進行替換,裡面封裝的是一組text文字以及其對應的action。

除了Toast以外,小夥伴們可以自行檢視: lightning:overlayLibrary(通過Modal 以及 popover展示訊息) / lightning:notificationsLibrary(通過notice和toast方式展示訊息)

上面既然已經描述完Toast的所有屬性以及Toast所能實現的功能,那麼我們接下來對常用的展示可以進行一些簡單的優化和處理。

場景一. 內容多行展示

Toast預設只能展示單行的內容,我們做了一個demo,將toast設定了sticky,這樣我們可以檢視到Toast的html的解析的實現,實現如下圖所示。通過圖片中的css內容我們可以看到toast的內容使用toastMessage forceActionsText兩個進行渲染,因為css渲染也有前後順序,我們只需要對這兩個css樣式進行重寫,設定white-space: pre-line !important; 即可,意為如果有空格情況下,合併所有空行並且保留換行,然後message中對需要換行的地方使用\n進行字串分隔即可從而實現換行的。

我們嘗試的在當前的component bundle的css重新渲染此樣式發現不可用,所以只能引入外部的static resource覆蓋此樣式。

.toastMessage.forceActionsText{
    white-space : pre-line !important;
}

方式為建立css,內容為上面描述的內容,然後命名上傳到 static resource,程式碼引入即可。demo中我們命名的static resource名稱為multipleLineToastCss。

程式碼中我們只需要<ltng:require styles="{!$Resource.multipleLineToastCss}"/>即可。

 我們做了簡單的demo去驗證:

<aura:component implements="flexipage:availableForAllPageTypes">
    <ltng:require styles="{!$Resource.multipleLineToastCss}"/>
    <lightning:button variant="brand" label="show toast" onclick="{!c.showToast}"/>
</aura:component>

對應的controller.js

showToast : function(component, event, helper) {
   var toastEvent = $A.get("e.force:showToast");
   toastEvent.setParams({
        mode: 'sticky',
        title: 'Info',
        type: 'info',
        message: 'test message\ntest multiple lines'
    });
    toastEvent.fire();
}

場景二.  Toast展示可點選的URL

某些場景下,我們需要展示Toast的時候搭配URL,使用者點選URL後跳轉到某個頁面。此種情況下我們只需要使用 messageTemplate 以及 messageTemplateData進行搭配即可實現。

showMyToast : function(component, event, helper) {
    var toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams({
        mode: 'sticky',
        message: 'This is a required message',
        messageTemplate: 'Record {0} created! See it {1}!',
        messageTemplateData: ['Salesforce', {
            url: 'http://www.salesforce.com/',
            label: 'here',
            }
        ]
    });
    toastEvent.fire();
}

 場景三. 換 Toast的message的圖示

我們知道當toast的type賦值時,針對success/warning/error/info都會有預設的樣式以及圖示,當我們需要展示其他的圖示時,我們只需要設定type為other或者不設定type(預設為other),然後設定key即可。key的話,我們可以找到lightning design system中的icon的名稱賦值即可。

showToast : function(component, event, helper) {
    var toastEvent = $A.get("e.force:showToast");
    toastEvent.setParams({
        mode: 'sticky',
        title: 'Info',
        type: 'other',
        key:'like',
        message: 'test message\ntest multiple lines'
    });
    toastEvent.fire();
}

 二. aura:method

很多內容我們可以進行公用的元件化操作,比如針對toast的展示(我們只需要設定方法傳遞引數,呼叫即可,不需要每個component的controller/helper js方法都重複的宣告Toast的宣告以及觸發),針對picklist值獲取,針對表字段label的獲取。製作公用組建需要先了解一個aura封裝的元件名稱,aura:method。

 我們在前端正常去進行方法呼叫通常是繫結一個handler或者執行某個事件從而去呼叫方法,使用aura:method定義一個方法可以作為元件的API的一部分,這樣我們在client-controller部分可以直接呼叫此方法。使用aura:method可以設定傳入的引數,也可以設定返回的同步或者非同步的結果,所以通常我們可以使用aura:method去做共用組建的內容,作為公用元件,使用aura:method去宣告,其他的component只需要引入此公用元件便有許可權直接呼叫aura:method宣告的方法了。

aura:method總共有以下的屬性:

  • name: 用來宣告方法的名稱,後期呼叫直接使用此方法呼叫,傳遞相關的引數即可;
  • action:此方法要去呼叫的client-controller的方法;
  • access:public(在相同namespace的component可以呼叫此方法) / global(在所有的namespace的component可以呼叫此方法);
  • description:方法描述。

除了以上屬性以外,方法還要有引數,使用aura:attribute去宣告方法體裡的引數項。aura:method可以實現同步以及非同步的返回,感興趣的可以檢視細節,下面內容為通過aura:method實現Toast公用元件。

ToastServiceComponent.cmp

<aura:component access="global">
    <ltng:require styles="{!$Resource.multipleLineToastCss}"/>

    <aura:method access="global" name="showToast" action="{!c.showToastAction}">
        <aura:attribute name="message" type="String" description="the body message will show. use \n to break lines" required="true"/>
        <aura:attribute name="displayTitle" type="String" description="the title hearder will show" required="true"/>
        <aura:attribute name="displayType" type="String" description="success/warning/error/info/other"/>
        <aura:attribute name="mode" type="String" description="dismissible/pester/sticky"/>
        <aura:attribute name="key" type="String" description="you can set name from lightning design system icon section"/>
    </aura:method>

</aura:component>

ToastServiceComponentController.js

({
    showToastAction : function(component, event, helper) {
        var params = event.getParam('arguments');
        var toastEvent = $A.get("e.force:showToast");
        var type = params.displayType;
        if(params.key) {
            type = 'other';
        }
        if(!params.mode) {
            params.mode = 'dismissible';
        }
        toastEvent.setParams({
            "title": params.displayTitle,
            "message": params.message,
            "type": type,
            "mode":params.mode,
            "key": params.key
        });

        toastEvent.fire();
    }
})

接下來是呼叫:

SimpleToastDemo.cmp:需要引入ToastServiceComponent,設定一個local id

<aura:component implements="flexipage:availableForAllPageTypes">
    <c:ToastServiceComponent aura:id="toastService"/>
    <lightning:button variant="brand" label="show toast" onclick="{!c.showToastHandler}"/>
</aura:component>

SimpleToastDemoController.js: find到aura:id,然後呼叫方法即可。

({
    showToastHandler : function(component, event, helper) {
        var toastService = component.find('toastService');
        toastService.showToast('this is a toast demo\n this can allow multiple lines\nhere we show like icon','simple toast demo','other','dismissible','like')
    }
})

展示如下:

 

 

 總結:篇中簡單介紹Toast以及aura:method,詳細瞭解的自行檢視文件,感興趣的最好了解一下 lightning:overlayLibrary以及lightning:notificationsLibrary。篇中有錯誤的地方歡迎指出,有不懂的歡迎留