【发布时间】:2019-02-01 11:50:35
【问题描述】:
我正在尝试编写一个@Prop 装饰器来帮助我设置自定义元素属性。
这是我想要实现的代码:
class MyClass extends HtmlElement {
get text() {
return this.getAttribute('text')
}
set text(newVal){
this.setAttribute('text', newVal)
}
connectedCallback() {
this.innerHTML = `<div>${this.text}</div>`
}
}
这是带有装饰器的类
class MyClass extends HtmlElement {
@Prop() text: string;
connectedCallback() {
this.innerHTML = `<div>${this.text}</div>`
}
}
这是装饰器函数
const Prop = () => (target : any, key : string) => {
const getter = () => target.getAttribute(key);
const setter = (newVal) => target.setAttribute(key, newVal);
if (!delete this[key]) return;
Object.defineProperty(target, key, {
get: getter,
set: setter
});
}
但是,每当调用 getter 函数时,我都会收到此错误:
Uncaught TypeError: Illegal invocation
at HTMLElement.getter (app.js:16)
查看app.js:16 会发现这行代码:
const getter = () => target.getAttribute(key);
target.getAttribute(key); 带有下划线。
【问题讨论】:
标签: typescript typescript-decorator