当使用 webcomponents-lite this.updateStyles 按预期工作。但是在不需要它的浏览器上,我不想加载它。
this.updateStyles 应该在没有 webcomponents-lite 的情况下工作吗?
非工作版本示例: http ://codepen.io/daKmoR/pen/dNPdya
class XFoo extends Polymer.Element {
static get is() { return 'x-foo'; }
static get config() {
return {
properties: {
width: {
type: String,
reflectToAttribute: true,
observer: '_onWidthChange'
}
}
};
}
constructor() {
super();
}
_onWidthChange(newValue, oldValue) {
console.log('setting width');
this.updateStyles({'--width': newValue});
}
}
customElements.define(XFoo.is, XFoo);
使用自己的 updateStyles 的解决方法示例:http: //codepen.io/daKmoR/pen/ggbeaR
class XFoo extends Polymer.Element {
static get is() { return 'x-foo'; }
static get config() {
return {
properties: {
width: {
type: String,
reflectToAttribute: true,
observer: '_onWidthChange'
}
}
};
}
constructor() {
super();
}
_onWidthChange(newValue, oldValue) {
console.log('setting width');
this.updateStyles({'--width': newValue});
}
updateStyles(obj) {
if (obj === undefined) {
return;
}
var str = '';
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str += p + ': ' + obj[p] + ';';
}
}
this.style = str;
}
}
customElements.define(XFoo.is, XFoo);
有没有更好的办法?