简体   繁体   中英

Using same LitElement multiple times in same page

Created web component using LitElement . I am using this component multiple times in the same page.

点击这里

I want to trigger one event only when my component is rendering first time on page.

What do you mean by "first time on page" ?

If you want the first time any instance renders in the current loaded page set window.someProperty before firing your event and then check it before firing the event again. Anything on window is cleared when the user navigates between pages, but if you're running an SPA (which Lit is particularly well suited to) that might not happen for a while.

If you want to do something the first time the element is loaded you can add the flag to the module that holds the element.

If you want each element to fire an event as it initially renders you can use firstUpdated .

If you want the first element somewhere in the document to fire an event then that's harder, as web components are all about isolated functionality - they aren't aware of other instances on the same page. Your best bet is to either:

  • Add a parent component that picks up events from all the sub-components and only does something the first time it gets one.
  • Add an index property that you increment for each instance and only have the event fire when it is 0 .

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