一百二十 salesforce零基礎學習快去遷移你的代碼中的 Alert / Confirm 以及 Prompt吧

本篇參考:
https://developer.salesforce.com/blogs/2022/01/preparing-your-components-for-the-removal-of-alert-confirm-prompt
https://help.salesforce.com/s/articleView?id=release-notes.rn_lc_alert_confirm_prompt.htm&type=5&release=238
https://developer.salesforce.com/docs/component-library/bundle/lightning-alert/documentation
https://developer.salesforce.com/docs/component-library/bundle/lightning-confirm/documentation
我們在項目中可能會用到 alert 或者 confirm方法來實現一些交互性效果 。比如不滿足指定的條件,我們需要alert提供一些文字來告訴用戶當前數據問題 , 引導用戶正確操作 。當我們對數據刪除或者對敏感信息修改時,可能需要彈出一個 confirm來實現強調效果 。
當然,上述內容可以通過toast或者 modal方式來實現 , 如果在項目中最開始使用了這些最好 , 但是既有的代碼就是存在使用了 alert / confirm / prompt的js方法了 , 很不幸的是 , 我們最好要替換掉這些方法避免不必要的問題 。https://github.com/whatwg/html/issues/5407 通過這個鏈接可以看到js的提案為不允許跨源iframes使用window的 alert / confirm / prompt.
【一百二十 salesforce零基礎學習快去遷移你的代碼中的 Alert / Confirm 以及 Prompt吧】當然這里有一個前提,就是 cross-origin,也就是說你的代碼里面盡管使用了這些,但是可能還可以正常運行 , 因為你沒有cross-origin 。目前谷歌以及safari的一些版本已經不再支持 , 所以為了避免后續不必要的問題,salesforce推薦我們遷移至安全的封裝好的組件上 。當然實際的UI會有一些區別,替換以前建議給客戶做demo看一下效果 。官方針對 classic場景以及aura / lwc都已經介紹了解決方案 。這里啰嗦一下 lwc這里的alert的一個實現 。
Lwc中使用 async/await 或者 .then()的方式來執行,而且這個組件可以在任何方法體內調用 。官方demo中使用的 async方式,demo中補一下 Promise方式 。Promise的then是在彈出的modal點擊OK以后調用的,所以如果方法中不需要針對OK以后執行什么操作,則可以使用 async / await方式,否則使用 .then,比如之前有 loading的spinner,當報錯展示 alert以后,需要將 spinner隱藏即可使用 Promise方式 。
myApp.html
<template><lightning-button onclick={handleAlertClick} label="Open Alert Modal"></lightning-button><template if:true={showSpinner}><lightning-spinner alternative-text="loading..."></lightning-spinner></template></template>myApp.js
import { LightningElement } from 'lwc';import LightningAlert from 'lightning/alert';export default class MyApp extends LightningElement {showSpinner = false;// async handleAlertClick() {//await LightningAlert.open({//message: 'this is the alert message',//theme: 'error', // a red theme intended for error states//label: 'Error!', // this is the header text//});////Alert has been closed// }handleAlertClick() {/*theme available optionsdefault: whiteshade: grayinverse: dark bluealt-inverse: darker bluesuccess: greeninfo: gray-ish bluewarning: yellowerror: redoffline: ?black*/this.showSpinner = true;LightningAlert.open({message: 'this is the alert message',theme: 'error', // a red theme intended for error stateslabel: 'Error!', // this is the header textvariant: "header"}).then((result) => {//當點擊OK按鈕以后的調用內容console.log('execute')this.showSpinner = false;});}}顯示效果

一百二十 salesforce零基礎學習快去遷移你的代碼中的 Alert / Confirm 以及 Prompt吧

文章插圖
總結:篇中只是針對這個功能簡單demo,詳情可以查看上方的文檔 。篇中有錯誤歡迎指出 , 有不懂歡迎留言 。

    推薦閱讀