首页 > 解决方案 > 如何将一个属性映射到 litElement 中的两个属性?

问题描述

我在一个 litElement 项目中工作,在一个组件中,我有一个属性需要映射到一个属性,并用一个函数计算到另一个属性,如下所示:


const calculateTwo(val) {
 return `${val} ${val}`
}

class MyElement extends LitElement {
  
  static get properties() {
    return {
      one: {
        type: String,
        attribute: 'foo',
      },
      two: {
        type: String,
        attribute: 'foo',
        reflect: false,
        converter: value => calculateTwo(value),
      },
    };
  }
}
<my-component foo="bar"></my-component>

如果我这样做,one不是用“bar”设置的,但是two是正确的

如果我删除该属性two,则one可以正常工作。

实现这一目标的更好方法是什么?

我可以使用该update功能,但我想知道是否有更好的方法。

我不想对属性之一使用 getter 函数,因为转换器的功能非常繁重,我不希望每次我想访问该道具时都调用它。

标签: javascriptweb-componentlit-elementlit-html

解决方案


我认为使用属性访问器可以避免调用两次渲染。

const calculateTwo(val) {
 return `${val} ${val}`
}

class MyElement extends LitElement {
  static get properties() {
    return {
      one: {
        type: String,
        attribute: 'foo',
      },
      two: {
        attribute: false
      }
    };
  }

  set one(value) {
    const oldValue = this._one;

    this.two = value;
    this._one = value;

    this.requestUpdate('one', oldValue);
  }

  get one() {
    return this._one;
  }

  set two(value) {
    const oldValue = this._two;

    this._two = calculateTwo(value);

    this.requestUpdate('two', oldValue);
  }

  get two() {
    return this._two;
  }
}

推荐阅读