咱們在lightning開發中,quick action是一個經常使用的功能,很惋惜的是,lwc目前還不支持單獨的custom quick action操做,只能嵌套在aura中使用才能發揮做用。html
官方也給咱們提供瞭如何進行嵌套,簡單代碼嵌套以下所示:flex
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId,flexipage:availableForRecordHome"> <!--This is a lwc component--> <c:testComponentForLwc> </aura:component>
咱們只須要聲明一個aura的components而後實現force:lightningQuickAction/force:lightningQuickActionWithoutHeader而且使用c:引入相關的lwc便可。這裏可能會提到兩個問題:ui
針對這兩個問題,咱們一個一個進行解決。this
針對第一個問題,咱們使用lightning:quickActionAPI 組件,而後調用其getSelectedActions方法獲取Promise而後解析便可實現。固然此組件還有不少常常用到的好用的功能,感興趣的小夥伴本身讀一下:https://developer.salesforce.com/docs/component-library/bundle/lightning:quickActionAPI/documentationspa
針對第二/三個問題,儘管lwc無法獲取或者關閉quick action,可是aura component是能夠的,咱們只須要在aura中進行事件監聽,而後在Lwc component中註冊事件便可實現。由於aura的事件監聽處理能夠捕捉到lwc的事件註冊。 OK,那咱們開始直接上代碼:設計
quickActionService.cmp:引入lightning:quickActionAPI從而能夠得到當前選擇的quick action name,而後根據quick action name去決定顯示哪一個lwc組件,而且對testLookUpFowLwc組件進行了兩個事件監聽處理,分別是refreshview以及closemodal。日誌
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId,flexipage:availableForRecordHome"> <aura:attribute name="quickActionName" type="String"/> <lightning:quickActionAPI aura:id="quickActionAPI" /> <aura:handler name="init" value="this" action="{!c.doInit}"/> <aura:if isTrue="{!v.quickActionName == 'Account.test_another'}"> <c:testLookUpForLwc onrefreshview="{c.refreshView}" onclosemodal="{!c.closeModal}"/> </aura:if> <aura:if isTrue="{!v.quickActionName == 'Account.test_action'}"> show area with test action </aura:if> </aura:component>
quickActionServiceController.js:對getSelectedActions進行解析,對事件調用force:event事件進行refresh view以及close action。code
({ doInit : function(component, event, helper) { var actionAPI = component.find("quickActionAPI"); actionAPI.getSelectedActions().then(function(result){ console.log(JSON.stringify(result)); if(result) { console.log(result.actions[0]); var actionName = result.actions[0].actionName; component.set('v.quickActionName',actionName); } }).catch(function(e){ }); }, refreshView : function(component,event,helper) { $A.get('e.force:refreshView').fire(); }, closeModal : function(component,event,helper) { $A.get("e.force:closeQuickAction").fire() } })
testLookUpForLwc.html:展現button,點擊button按鈕執行handleClosecomponent
<template> <lightning-button type="button" label="submit and close" variant="brand" onclick={handleClose}></lightning-button> </template>
testLookUpForLwc.js:方法註冊refreshview以及closemodal事件,從而讓父去監聽以及執行事件。htm
import { LightningElement,track } from 'lwc'; export default class TestLookUpForLwc extends LightningElement { handleClose(event) { this.dispatchEvent(new CustomEvent('refreshview')); this.dispatchEvent(new CustomEvent('closemodal')); } }
顯示效果:咱們在account上建立兩個quick action,分別是test_action以及test_another,分別綁定了這個aura,當咱們點擊之後test_action之後,打印出來的日誌結果。
總結:篇中主要講述lwc如何配合aura實現quick action以及相關的refresh / close 的功能,針對refresh / close不止針對quick action,針對其餘的lwc的設計一樣有效。篇中有錯誤地方歡迎指出,有問題歡迎留言。