簡體   English   中英

如何在 stencil.js/tsx 中定義全局變量?

[英]How to define global variables in stencil.js/tsx?

如何在 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 變量,這樣我就可以在兩個函數中使用它。

您可以將其設置為 state,如下所示。

    @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');
        }

希望對你有幫助:)

根據 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');
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM