本篇參考:
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.
當然這裏有一個前提,就是 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 options default: white shade: gray inverse: dark blue alt-inverse: darker blue success: green info: gray-ish blue warning: yellow error: red offline: black */ this.showSpinner = true; LightningAlert.open({ message: 'this is the alert message', theme: 'error', // a red theme intended for error states label: 'Error!', // this is the header text variant: "header" }).then((result) => { //當點擊OK按鈕以後的調用內容 console.log('execute') this.showSpinner = false; }); } }
顯示效果
總結:篇中只是針對這個功能簡單demo,詳情可以查看上方的文檔。篇中有錯誤歡迎指出,有不懂歡迎留言。