Salesforce LWC子组件向父组件通信

601 阅读1分钟

LWC支持组件间的通信,本篇描述第一种情况。之前也学了点VUE.js,感觉LWC组件通信与VUE有点类似,不过VUE基本已经忘光,所以就不做对比了!

image.png

1.新建父组件numerator

numerator.html

<template>
    <lightning-card title="Numerator" icon-name="action:manage_perm_sets">
        <p class="slds-text-align_center slds-var-m-vertical_medium">
            Count: <lightning-formatted-number value={counter}></lightning-formatted-number>
        </p>
        <c-controls class="slds-show slds-is-relative" 
            onadd={handleIncrement} 
            onsubtract={handleDecrement} 
            onmultiply={handleMultiply}>
        </c-controls>
    </lightning-card>
</template>

numerator.js

import { LightningElement } from 'lwc';

export default class Numerator extends LightningElement {
    counter = 0;
    
    handleIncrement() {
        this.counter++;
    }
    
    handleDecrement() {
        this.counter--;
    }
    
    handleMultiply(event) {
        const factor = event.detail;
        this.counter *= factor;
    }
}

numerator.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>55.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
      <target>lightning__AppPage</target>
    </targets>
</LightningComponentBundle>

2.新建子组件Controls

controls.html

<template>
    <lightning-card title="Controls" icon-name="action:upload">
        <lightning-layout>

            <lightning-layout-item flexibility="auto" padding="around-small">
                <lightning-button label="Subtract" icon-name="utility:dash" onclick={handleSubtract}>
                </lightning-button>
            </lightning-layout-item>

            <lightning-layout-item flexibility="auto" padding="around-small">
                <lightning-button label="2" data-factor="2" icon-name="utility:close" onclick={handleMultiply}>
                </lightning-button>
                <lightning-button label="3" data-factor="3" icon-name="utility:close" onclick={handleMultiply}>
                </lightning-button>
            </lightning-layout-item>

            <lightning-layout-item flexibility="auto" padding="around-small">
                <lightning-button label="Add" icon-name="utility:add" onclick={handleAdd} icon-position="right">
                </lightning-button>
            </lightning-layout-item>

        </lightning-layout>
    </lightning-card>
</template>

controls.js

import { LightningElement } from 'lwc';

export default class Controls extends LightningElement {
    handleAdd() {
        this.dispatchEvent(new CustomEvent('add'));
    }
    
    handleSubtract() {
        this.dispatchEvent(new CustomEvent('subtract'));
    }
    
    handleMultiply(event) {
        const factor = event.target.dataset.factor;
        this.dispatchEvent(new CustomEvent('multiply', {
            detail: factor
        }));
    }
}

image.png

numerator.html中,引用了controls子组件,在父组件上on+事件名用于监听子组件向父组件传递的事件,如onadd,子组件是通过this.dispatchEvent(new CustomEvent('add'))向父组件通知需要执行add事件,父组件通过onadd监听子组件是否触发add事件,当add事件触发时,父组件就会执行handleIncrement方法。
如果子组件需要携带参数到父组件,在CustomEvent第二个参数加上携带的数据,如this.dispatchEvent(new CustomEvent('multiply', { detail: 2 })),父组件在执行方法handleMultiply时,通过获取event.detail获取子组件传递的值

若父组件不采用onclick,改为onbuttonclick,那handleIncrement方法就不会被执行,也就是说子组件传递的事件不会被父组件监听到,这时候需要在子组件CustomEvent携带多一个键值{ bubbles: true },this.dispatchEvent(new CustomEvent('multiply', { detail: 2 , bubbles: true }))

参考文档:[1]Communicate from Parent to Child-Trailhead[2]Configure Event Propagation-LWC文档