我在一个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函数,因为转换器的函数很重,而且我不想每次访问属性时都调用它。
发布于 2020-06-25 10:43:04
我认为使用属性访问器可以避免两次调用呈现。
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;
}
}
发布于 2020-06-25 10:06:09
如果您不想应用getter,那么updated
是您最好的选择
const calculateTwo(val) {
return `${val} ${val}`
}
class MyElement extends LitElement {
static get properties() {
return {
one: {
type: String,
attribute: 'foo',
},
two: {
attribute: false
}
};
}
updated(changed) {
if (changed.has('one')
this.oneChanged()
}
oneChanged() {
this.two = calculateTwo(this.one);
}
}
https://stackoverflow.com/questions/62570433
复制