ruby-on-rails Rails 7 -刺激控制器看不到html目标

qzlgjiam  于 2023-05-02  发布在  Ruby
关注(0)|答案(1)|浏览(201)
import { Controller } from "@hotwired/stimulus";
import consumer from "channels/consumer";

export default class extends Controller {
  static targets = ["users", "roomId"]

  connect() {

    this.subscription = consumer.subscriptions.subscriptions.find(subscription => 
    subscription.identifier === '{"channel":"RoomChannel"}');

    console.log("CONNECTED")

    console.log("Connected to room controller");
    console.log("Element: ", this.element);
    console.log("Users target: ", this.usersTarget);
    console.log("Room ID target: ", this.roomIdTarget);

    this.subscription.received = this.received.bind(this);

   }

}

HTML:

<div data-controller="room">
  <p>Joined users: <span data-target="users"></span></p>
  <p>Room ID: <span data-target="roomId"></span></p>
</div>

开发工具日志:
1.联系我们
1.接房间控制器

<div data-controller="room">
  <p>Joined users: <span data-target="users"></span></p>
  <p>Room ID: <span data-target="roomId"></span></p>
</div>

和4)

Error connecting controller

Error: Missing target element "users" for "room" controller
6qqygrtg

6qqygrtg1#

根据Stimulus文档-您必须在目标属性名称中包含控制器标识符。
https://stimulus.hotwired.dev/reference/targets

<div data-controller="room">
  <p>Joined users: <span data-room-target="users"></span></p>
  <p>Room ID: <span data-room-target="roomId"></span></p>
</div>

我相信旧版本的刺激计划没有要求这一点,但最新版本有。这样做的原因是,可以让多个控制器以同一元素为目标,而不会发生名称冲突。

相关问题