如何使用LitElement观察属性更改

gro*_*hjy 6 polymer lit-element

我不知道如何在LitElement中观察属性变化.

我一直在尝试这些方法,但我无法让这些方法起作用:

  static get properties() {
    return {
      temp1:String,
      temp2: {
       type:String,
       observer: '_temp2Changed'
        }
  };

  temp1Changed(newValue, oldValue){
    console.log("temp1 changed")
  }
  _temp2Changed(newValue, oldValue){
    console.log("temp2 changed")
  }
Run Code Online (Sandbox Code Playgroud)

Mic*_*zko 8

版本0.6.0+

首先,您必须指定元素属性.您可以通过创建静态getter来执行此操作,该getter返回一个对象,包括其名称作为键及其属性相关配置.

updated时变特性造成了重新绘制的生命周期方法被调用.第一个参数将在更新之前返回值.

class MyComponent extends LitElement {
  static get properties() {
    return {
      foo: {}
    };
  }

  constructor() {
    super();
    this.foo = 0;
    setInterval(() => this.foo++, 1000);
  }

  updated(changedProperties) {
    console.log(changedProperties); // logs previous values
    console.log(this.foo); // logs current value
  }

  render() {
    return html`${this.foo}`;
  }
}

customElements.define("my-component", MyComponent);
Run Code Online (Sandbox Code Playgroud)


gro*_*hjy 0

我从 Polymer 的 PWA 入门套件中找到了解决方案。

将以下内容添加到您的元素定义中:

_propertiesChanged(props, changed, oldProps) {
    console.log("_propertiesChanged(props, changed, oldProps):");
    console.log(props);    
    console.log(changed);  
    console.log(oldProps); 
    if (changed && 'temp1' in changed) {
      console.log("if temp1:"+changed.temp1);
    }
    super._propertiesChanged(props, changed, oldProps); //This is needed here
}

console output:
_propertiesChanged(props, changed, oldProps):
{temp1: "newVal1", temp2: "val2"}
{temp1: "newVal1"}
{temp1: "val1"}
if temp1:newVal1
Run Code Online (Sandbox Code Playgroud)