LWC越来越便利了,本次更新内容值得一看!
此维护模块分为两部分,第一部分是选择题,仔细阅读文章后都能答对,所以我直接给出第二部分代码示例,仅供参考。
①.Child LWC (只需要js, 其余默认新建即可):
import { LightningElement, api } from "lwc";
import LightningAlert from "lightning/alert";
export default class Child extends LightningElement {
@api
async sayHi() {
await LightningAlert.open({
message: "Hello Trailblazer!",
theme: "success",
label: "Greetings"
});
console.log("Alert modal has been closed");
}
}
②.Parent LWC (需要将本次更新应用到维护模块中的示例代码上):
import { LightningElement, api, wire } from "lwc";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import FIELD_NAME from "@salesforce/schema/Account.Name";
import FIELD_OWNER_NAME from "@salesforce/schema/Account.Owner.Name";
import FIELD_PHONE from "@salesforce/schema/Account.Phone";
import FIELD_INDUSTRY from "@salesforce/schema/Account.Industry";
export default class Parent extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: "$recordId", fields: [FIELD_NAME, FIELD_INDUSTRY], optionalFields: [FIELD_PHONE, FIELD_OWNER_NAME] })
account;
get name() {
return getFieldValue(this.account.data, FIELD_NAME);
}
get phone() {
return getFieldValue(this.account.data, FIELD_PHONE);
}
get industry() {
return getFieldValue(this.account.data, FIELD_INDUSTRY);
}
get owner() {
return getFieldValue(this.account.data, FIELD_OWNER_NAME);
}
sayHi() {
let cmp = this.refs.child; //无需querySelector()即可取得DOM元素
cmp.sayHi();
}
}
<template>
<lightning-card title="Summer '23 Maintenance">
<lightning-button slot="actions" label="Say Hi" onclick={sayHi}></lightning-button>
<template lwc:if={account.data}> <!--取代了原先的if:true-->
<div class="slds-m-around_medium">
<p>Account Name: {name}</p>
<p>Industry: {industry}</p>
<p>Phone: {phone}</p>
<p>Owner: {owner}</p>
</div>
</template>
<template lwc:else> <!--取代了原先的if:false-->
<div class="slds-m-around_medium slds-text-color_destructive">An error occurred while retrieving data</div>
</template>
<c-child lwc:ref="child"></c-child> <!--js中的this.refs.child ,就是它-->
</lightning-card>
</template>
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object> <!--指定到Account record页面-->
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>