AlpineJS:如何有条件地向元素添加类? [英] AlpineJS: How can I add a class to an element conditionally?
问题描述
感谢Laravel Echo,Livewire和AlpineJS,我收到了一系列消息.
I have an array of messages being pulled into view thanks to Laravel Echo, Livewire, and 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
,但是我似乎无法像使用Blade那样使AlpineJS在条件逻辑中很好地发挥作用.
I want to dynamically add a class called chat-block-author
when the rendered message belongs to the logged-in user. The Message
model does contain user_id
for each item, but I can't seem to get AlpineJS to play well with conditional logic like I could with Blade.
有什么提示吗?
这不起作用
<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中,您可以通过执行以下操作来动态分配包括类在内的任何属性:
You did not mention where you want to add that class to, but in AlpineJS you can dynamically assign any attribute including classes by doing something like this:
<div :class="{ 'chat-block-author': message.user_id === {{ Auth::user()->id }} }" class="your-other-classes go-here">
...
</div>
请注意,您还可以将其与现有的class属性一起使用,如果指定的条件为true,则将:class
中定义的属性动态添加到您的class属性中.
Note that you can also use it with an existing class attribute, the attributes defined in :class
are dynamically added to your class attribute if the specified condition is true.
这篇关于AlpineJS:如何有条件地向元素添加类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!