简体   繁体   中英

LitElement: Call a Method from external web component

I'm very new to Lit and Web Components. I hope you can help me.

I wrote the following Element:

import {html, LitElement, PropertyValues} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import "@ui5/webcomponents/dist/Toast.js";
import {connect} from "pwa-helpers";
import {store} from "../redux/store.js";
import {Toast} from "../_interface/toast.js";

@customElement('md-toast-view')
export class ToastView extends connect(store)(LitElement) {

  @property()
  private toast: Toast;

  @property()
  private readonly defaultMessage: string =  "";

  private readonly componentID: string = "md-toast"

  constructor() {
    super();
    this.toast = {
      message: this.defaultMessage
    }
  }

  stateChanged(state: any) {
    this.toast = state.toast.toast;
  }

  render() {
    if (this.toast.message === "") {
      console.log("Message is null")
      return html``;
    }

    return html`
      <ui5-toast id="${this.componentID}">${this.toast.message}</ui5-toast>
    `;
  }


  protected updated(_changedProperties: PropertyValues) {
    if (_changedProperties.has('toast')){
      console.log("Toast has updated");
      const element = this.renderRoot.querySelector('#'+this.componentID);
      console.log(element)
      if (element !== null){
        element.dispatchEvent(new CustomEvent('show'))
      }
    }
  }
}

The idea is that when a message is stored in the redux store that a toast is given. The toast itself is from the following website: https://sap.github.io/ui5-webcomponents/playground/components/Toast/

As you can see, the ui5 component has a public method "show", which must be triggered.

Currently, I've gotten as far as triggering the updated method from my LitElement and getting the UI5 component. But somehow, the "dispatchEvent" method does not trigger the ui5 component.

The console output looks like this:

在此处输入图像描述

Thank you for helping me

As you can see, the ui5 component has a public method "show", which must be triggered called .

show as you mentioned is a method . Just call it:

element.show();

No need to dispatch an event on the component. Components are meant communicate changes to their internal state via events upwards ; to actively trigger state changes from the outside, use the component's API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM