5

我想为我的控制器的 CSS 选择器设置一个 const 变量,而不是在整个控制器中对其进行硬编码。我已将声明放在控制器的 initialize() 中,但出现未声明变量的错误。这样做的正确方法是什么?

当前尝试

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = ["form"]

  initialize() {
    const seasonInputSelector = "input[id$='_season']"
  }

  change(event) {
    // ...
    var yearNodes = this.formTarget.querySelectorAll(seasonInputSelector)
    // ...
  }

}

错误: ReferenceError:未定义 seasonInputSelector

4

2 回答 2

7

const在模块的根范围内使用变量:

import { Controller } from "stimulus"

const seasonInputSelector = "input[id$='_season']";

export default class extends Controller {
  static targets = ["form"]

  initialize() {
  }

  change(event) {
    // ...
    var yearNodes = this.formTarget.querySelectorAll( seasonInputSelector );
    // ...
  }

}
于 2020-06-27T19:40:59.483 回答
3

另一种方法是在你的班级范围内

import { Controller } from "stimulus"

export default class extends Controller {
  static targets = ["form"]
  seasonInputSelector = "input[id$='_season']";

  change(event) {
    // ...
    var yearNodes = this.formTarget.querySelectorAll( this.seasonInputSelector );
    // ...
  }
}
于 2020-07-02T09:17:53.673 回答