如何在Stencil.js组件中定义全局变量?
@ClickOutside()
someMethod() {
let editable = this.el.querySelector('.editable');
if (this.el.classList.contains('is-open')) {
this.el.classList.toggle('is-open');
editable.setAttribute('contenteditable',
editable.getAttribute('contenteditable') === 'true' ? 'false' : 'true');
}
}
openToolbar() {
let editable = this.el.querySelector('.editable');
if (editable.getAttribute('contenteditable') === 'true') {
return
}
this.el.classList.toggle('is-open');
editable.setAttribute('contenteditable',
editable.getAttribute('contenteditable') === 'true' ? 'false' : 'true');
}
这按预期工作,但是我在两个单独的功能中重复我自己。我想在外部定义第一个let变量,以便可以在两个函数中使用它。
答案 0 :(得分:0)
您可以将其设置为以下状态。
@State() editable;
componentWillLoad() {
this.editable = this.el.querySelector('.editable');
}
@ClickOutside()
someMethod() {
if (this.el.classList.contains('is-open')) {
this.el.classList.toggle('is-open');
editable.setAttribute('contenteditable',
editable.getAttribute('contenteditable') === 'true' ? 'false' : 'true');
}
}
openToolbar() {
if (editable.getAttribute('contenteditable') === 'true') {
return
}
this.el.classList.toggle('is-open');
editable.setAttribute('contenteditable',
editable.getAttribute('contenteditable') === 'true' ? 'false' : 'true');
}
希望这会对您有所帮助:)
答案 1 :(得分:0)
根据Koga的提示,这对我有用:
@State() editable;
componentDidLoad() {
this.editable = this.el.querySelector('.editable');
}
@ClickOutside()
someMethod() {
if (this.el.classList.contains('is-open')) {
this.el.classList.toggle('is-open');
this.editable.setAttribute('contenteditable',
this.editable.getAttribute('contenteditable') === 'true' ? 'false' : 'true');
}
}
openToolbar() {
if (this.editable.getAttribute('contenteditable') === 'true') {
return
}
this.el.classList.toggle('is-open');
this.editable.setAttribute('contenteditable',
this.editable.getAttribute('contenteditable') === 'true' ? 'false' : 'true');
}