網站搜尋

typescript - 在 lit-element 繪製後執行函數


我希望在兩個 lit-element 的更改已經被繪製/渲染到螢幕上之後執行一個函數。

我想出了以下方法,但我想知道:(a) 它正確嗎?(我有正確使用 requestAnimationFrame 嗎?)(b) 有沒有更好的方法?

changeElementPropertiesWhichCauseRedraw(this.ele1, this.ele2);

Promise.all([this.ele1.updateComplete, this.ele2.updateComplete])
  .then(() => window.requestAnimationFrame(() => setTimeout(() => afterPaint())));

答案#1

幸運的是,有一個現成的生命週期方法正好符合你的需求。在你的 lit-element 元件中,你需要實作以下內容:

  firstUpdated() {
    super.firstUpdated();
    // your code goes here
  }

當您的元素首次渲染時調用。在元素的生命週期中只調用一次。對於需要訪問 DOM 的一次性設置工作很有用。

參考資料:https://open-wc.org/guides/knowledge/lit-element/lifecycle/