在多个地方使用Stimulus Controller

4
我希望在Web应用程序的多个位置使用刺激控制器。我想做类似于这样的事情:
<div data-controller="mycontroller">
  <OneComponent />
</div>

<SomeOtherComponent />

<div data-controller="mycontroller">
  <NewComponent />
</div>

但是控制器似乎只连接到了第一个组件,而没有连接到第二个组件。我打算的用法可行吗?

谢谢!


1
你能发布一下你组件的代码吗? - Duderino9000
Stimulus 肯定可以处理这个问题(我有自己的 Stim 控制器,在一个页面上最多使用 10 次)。你怎么知道它只连接到一个元素? - aidan
1
因为在connect()函数中只打印了第一个组件。 - Rafael Mora
1个回答

1

刺激控制器可以重复使用。请参考此示例。

可能会阻止其正常工作的问题是JS错误,或者您期望在嵌套组件中使用的元素在父组件中使用,如果它们尚未呈现。

const application = Stimulus.Application.start()

application.register("hello", class extends Stimulus.Controller {
  connect() {
    console.log("connect to", this.element.getAttribute("data-language"))
  }
  
  static get targets() {
    return [ "name" ]
  }
  
  greet() {
    if (this.element.getAttribute("data-language") == "es-ES") {
      console.log(`¡Hola, ${this.nameTarget.value}!`);
    } else {
      console.log(`Hello, ${this.nameTarget.value}!`);
    }
  }
})
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <script src="https://unpkg.com/stimulus/dist/stimulus.umd.js"></script>
</head>
<body>
  <div data-controller="hello" data-language="en-US">
    <input data-hello-target="name" type="text" value="John">
    <button data-action="click->hello#greet">Greet</button>
  </div>
  
  <div data-controller="hello" data-language="es-ES">
    <input data-hello-target="name" type="text" value="Jose">
    <button data-action="click->hello#greet">Saudar</button>
  </div>
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接