由于Laravel Echo, Livewire和AlpineJS,我有一个消息数组被拉入视图。
<div class="mt-4 rounded-lg p-6"
x-data="{{ json_encode(['messages' => $messages, 'messageBody' => '']) }}"
x-init="
Echo.join('demo')
.listen('MessageSentEvent', (e) => {
@this.call('incomingMessage', e)
})
">
<template x-if="messages.length > 0">
<template
x-for="message in messages"
:key="message.id"
>
<div class="my-8">
<div class="flex flex-row justify-between border-b border-gray-200">
<span class="text-white-600 chat-block-author" x-text="message.user.name"></span>: <span class="text-white-800" x-text="message.body" style="margin-left:10px;"></span>
</div>
</div>
</template>
</template>
</div>
当呈现的消息属于登录用户时,我想动态地添加一个名为chat-block-author
的类。Message
模型确实包含每个项目的user_id
,但我似乎无法让AlpineJS与条件逻辑玩得很好,就像我可以用刀锋。
提示吗?
这行不通
<template x-if="message.user_id == {{ Auth::user()->id }}">
<div class="my-8">
<div class="flex flex-row justify-between border-b border-gray-200">
<span class="text-white-600 chat-block-author" x-text="message.user.name"></span>: <span class="text-white-800" x-text="message.body" style="margin-left:10px;"></span>
</div>
</div>
</template>
,因为它产生这个错误
Uncaught (in promise) ReferenceError: message is not defined
at eval (eval at tryCatch.el.el (alpine.js?df24:1), <anonymous>:3:36)
at tryCatch.el.el (alpine.js?df24:140)
at tryCatch (alpine.js?df24:127)
at saferEval (alpine.js?df24:135)
at Component.evaluateReturnExpression (alpine.js?df24:1747)
at eval (alpine.js?df24:1714)
at Array.forEach (<anonymous>)
at Component.resolveBoundAttributes (alpine.js?df24:1696)
at Component.updateElement (alpine.js?df24:1672)
at eval (alpine.js?df24:1628)
你没有提到你想在哪里添加这个类,但在AlpineJS中,你可以动态地分配任何属性,包括类,通过这样做:
<div :class="{ 'chat-block-author': message.user_id === {{ Auth::user()->id }} }" class="your-other-classes go-here">
...
</div>
注意,您也可以将它与现有的类属性一起使用,如果指定的条件为真,则在:class
中定义的属性将动态添加到您的类属性中。