本篇參考:
https://developer.salesforce.com/docs/platform/lwc/guide/create-components-dom-work.html?q=ref#refs
https://developer.salesforce.com/docs/platform/lwc/guide/reference-directives.html
一. Flow debug as other user
隨着項目上的Flow的使用越來越多,我們也需要多關注Flow的一些有用的功能。今天整理的是Debug Flow as other user。我們在項目中偶爾有需求是針對指定的Profile/Role進行某些操作,比如我們的需求是當User Profile是Custom: Sales Profile 並且創建Account數據時,不允許創建Account Type是Channel Partner / Reseller的數據。我知道這個需求可以通過Validation Rule解決,這裏只是舉一個例子引出我們後續的內容。
當我們創建好這個flow以後,我們最好在flow active以前做好所有的測試,所以debug是必不可少的環節。因爲我們當前的user並不是這個profile,所以如何進行測試呢? 我們可以在Process Automation Settings中啓用標紅的選項。
當我們勾選以後進入Flow,點擊debug按鈕以後勾選 Run flow as another user便可以解決此種類似的問題。
二. lwc中使用Refs獲取元素
我們以前獲取元素可以通過template.querySelector,除此以外,我們還可以通過ref標記component,然後js端快速獲取。以下爲簡單例子:
refSample.html: 組件元素通過lwc:ref屬性設置
<template> <lightning-input type="text" label="Demo" lwc:ref="demo"></lightning-input><br/> <lightning-button label="output Demo Value" onclick={handleOutputAction}></lightning-button><br/> {outputValue} </template>
refSample.js:js中可以直接使用全局變量 this.refs. + 在html中聲明的名稱即可獲取到對應的組件元素。
import { LightningElement, track, wire } from 'lwc'; export default class refSample extends LightningElement { outputValue; handleOutputAction(event) { //以下兩種寫法都可以正常的獲取 this.outputValue = this.refs.demo.value; // this.outputValue = this.template.querySelector('lightning-input').value; } }
lwc:ref也是有一些限制的:
- 只讀類型,不能set value;
- 不能用於 template或者slot元素上。比如這種聲明就會報錯。
<template lwc:ref="myTemplate"></template>
- 不能用於for:each 或者 iterator循環中。
- 使用前需要聲明,如果獲取不到,返回undefined。(這裏做一下擴展,我們在開發時,可能html端聲明瞭lwc:ref但是這個在 template:if中,如果值爲false,組件不渲染,後臺通過 refs獲取還是爲 undefined,所以獲取以後儘量的判斷一下是否 undefined)
總結:本篇整理了兩個項目中可能會用到的小特性,篇中有錯誤地方歡迎指出,有不懂歡迎留言。