0

我正在建立一个倒计时,除非向构造函数添加超时,否则没有 HTML 属性(计数、宽度、颜色、颜色、显示)值:

JS:

import {LitElement, html} from 'lit';

class ProgressBar extends LitElement
{ 
  static get properties()
  {
    return {
      count:      {type: Number},
      width:      {type: Number},
      color:      {type: String},
      colorback:  {type: String},
      display:    {type: String}
    }
  }  

  render()
  {
    let output = '';
    if(this.display==='true')
    {
      output = html`
      <style>
      :host > div
      {
        background-color: ${this.colorback};
        width: 100%;
      }
      :host > div > div
      {
        background-color: ${this.color};
        width: ${this.width}%;
        height: 30px;
      }            
      </style>
      <div>
        <div></div>
      </div>
    `;
    }
    return output;
  }

  draw()
  {
    let self = this
    
    let x = self._date_end - (+new Date());
    self.width = x * 100 / self.count

    if(self.width>0)
    {
      window.setTimeout(function()
      {
        self.draw()
      }, 1000 / 60)
    }
    else
      self.width = 0
  }

  main()
  {
    let self        = this
    self._date_end  = new Date((+new Date())+self.count);
    self.draw()
  }

  constructor()
  {
    super()
    let self = this
    // working
    window.setTimeout(function()
    {
      self.main()
    }, 1000)
    // not working
    self.main()
  }   
}

window.customElements.define('progress-bar', ProgressBar)

HTML:

<!DOCTYPE html>
<html>
    <head>
    </head>
    <body>
        <progress-bar
            display="true"
            width="100"
            color="#4cAf50"
            colorback="#ddd"
            count="5000">
        </progress-bar>
        <script src="main.js"></script>
    </body>
</html>

如何处理?谢谢

4

1 回答 1

2

使用connectedCallback方法可以正常工作:

connectedCallback()
{
    super.connectedCallback()        
    this.main()
}

constructor()
{
    super()
}  

https://lit.dev/docs/components/lifecycle/#connectedcallback

于 2021-11-23T12:29:27.837 回答