javascript - 如何将一个属性映射到 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 函数,因为转换器的功能非常繁重,我不希望每次我想访问该道具时都调用它。
解决方案
我认为使用属性访问器可以避免调用两次渲染。
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;
}
}
推荐阅读
- cefsharp - DevTools windowOpen 事件未从 Cef/CefSharp 触发
- python - AttributeError:模块“jaxlib.xla_extension”没有属性“PmapFunction”
- clickhouse - 如何为clickhouse创建索引?
- data-structures - 如果在链接列表中进行无限插入会发生什么?
- reactjs - 防止重新渲染子级以供使用PDF updateInstance()
- python - ValueError:时间数据“2021-11-11 05:01:12.11111”与格式“%Y-%m-%d %H:%M:%S %p”不匹配
- python - 有谁知道为什么我没有得到输出,代码编译但不返回输出
- python - Groupby年月并在Python中查找前N个最小值列
- python - 根据另一个列表对列表进行排序
- node.js - MongoDB 环境变量错误,不确定如何继续