试图通过单击另一个按钮来模拟鼠标单击一个按钮。目标是在整个页面中重用单个自定义按钮的行为。为什么dispatchEvent
不工作?
如何<c-custom-button>
模拟点击?
父应用程序.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!'
}
}