我的 Rails 6 应用程序出现错误,因为它找不到我的数据目标,但我不明白为什么。
Chrome 控制台中的错误:
Uncaught Error: Missing target element "channel.messages"
我的观点:
<div class="col-sm-10" data-controller="channel" data-channel-id="<%= @channel.id %>">
<!-- Chat messages -->
<div class="pr-6 py-4 flex-1">
<div data-target="channel.messages">
<%= render @channel.messages %>
</div>
<div class="pb-6 pr-4 flex-none">
<div class="flex rounded-lg border-2 border-grey overflow-hidden">
<span class="text-3xl text-grey border-r-2 border-grey p-2">
<svg class="fill-current h-6 w-6 block" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20"><path d="M16 10c0 .553-.048 1-.601 1H11v4.399c0 .552-.447.601-1 .601-.553 0-1-.049-1-.601V11H4.601C4.049 11 4 10.553 4 10c0-.553.049-1 .601-1H9V4.601C9 4.048 9.447 4 10 4c.553 0 1 .048 1 .601V9h4.399c.553 0 .601.447.601 1z"/></svg>
</span>
<input type="text" class="w-full px-4" placeholder="Message <%= @other_user.name %>" />
</div>
</div>
</div>
</div>
<%= form_with model: [@channel, Message.new], data: { action: "ajax:success->channel#clearMessage" } do |form| %>
<%= form.text_field :body, class: "form-control", data: { target: "channel.newMessage" } %>
<% end %>
</div>
_messages 部分:
<div>
<div class="font-weight-bold"><%= message.user.name %></div>
<div><%= message.body %></div>
</div>
我的控制器:
import { Controller } from "stimulus"
import consumer from "channels/consumer"
export default class extends Controller {
static targets = [ "messages", "newMessage" ]
connect() {
this.subscription = consumer.subscriptions.create({ channel: "MessageChannel", id: this.data.get("id") }, {
connected: this._connected.bind(this),
disconnected: this._disconnected.bind(this),
received: this._received.bind(this)
})
}
disconnect() {
consumer.subscriptions.remove(this.subscription)
}
_connected() {
}
_disconnected() {
}
_received(data) {
if (data.message) {
this.messagesTarget.insertAdjacentHTML('beforeend', data.message)
}
}
clearMessage(event) {
this.newMessageTarget.value = ''
}
}
当我检查 HTML 时,它显示:
<div data-target="channel.messages">