salesforce lightning零基礎學習(十四) 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。篇中有錯誤的地方歡迎指出,有不懂的歡迎留言。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理

【其他文章推薦】

※如何讓商品強力曝光呢? 網頁設計公司幫您建置最吸引人的網站,提高曝光率!!

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

※幫你省時又省力,新北清潔一流服務好口碑

※別再煩惱如何寫文案,掌握八大原則!

您可能也會喜歡…