【问题标题】:LWC Create and Dispatch Event Does Not WorkLWC 创建和调度事件不起作用
【发布时间】:2020-08-28 16:27:46
【问题描述】:

试图通过单击另一个按钮来模拟鼠标单击一个按钮。目标是在整个页面中重用单个自定义按钮的行为。为什么dispatchEvent 不起作用?

如何模拟点击<c-custom-button>?

parentApp.html

<template>
    <div>
        <c-custom-button
            label="New">
        </c-custom-button>
    </div>
    <div>
        <lightning-button
            label="Call New"
            onclick={simulateClick}>
        </lightning-button>
    </div>
</template>

parentApp.js

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {

    cButtonElement;

    simulateClick() {
        this.cButtonElement = this.template.querySelector('c-custom-button');
        let clickEvent = new CustomEvent('click');
        this.cButtonElement.dispatchEvent(clickEvent);
    }

}

customButton.html

<template>
    <lightning-button
        label={label}
        icon-name="utility:new"
        onclick={handleClick}>
    </lightning-button>
</template>

customButton.js

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    @api label;

    handleClick() {
        this.label = 'CLICKED!'
    }
}

【问题讨论】:

    标签: salesforce-lightning lwc


    【解决方案1】:

    感谢Nathan Shulman for helping with this。

    在 parentApp.js 中添加对子方法的调用

        simulateClick() {
            this.cButtonElement = this.template.querySelector('c-custom-button');
            this.cButtonElement.handleClick();
        }
    

    将@api 装饰器添加到customButton.js 中的方法

        @api handleClick() {         
            this.label = 'CLICKED!'
        }
    

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-28
      • 2017-05-24
      相关资源
      最近更新 更多