如何保持按钮集中在点击按钮与高山js?



我使用laravel 8部署了一个简单的调查表单。当用户点击评级按钮时,按钮颜色会发生变化,但问题是当用户点击时,它应该只关注被点击的按钮。我需要点击按钮的颜色被改变,并保持专注于它,即使用户点击外面。我如何用alpine js实现这一点?

下面的代码是刀片文件。我正在循环显示来自控制器页面的一个数组中的问题和评分按钮。

<div>
@foreach ($formDetail as $num => $row)
<div class="grid grid-cols-1 mt-2 p-4" wire:model.defer="formDetail.{{$num}}.question">{{$formDetail[$num]['question']}}</div>
<div class="flex flex-nowrap gap-2 p-6">
@foreach ($ratings as $index => $r)
<div   x-data="{click:false}">
<button type="button"   @click="click=true" :class="click?'bg-red-400':'bg-green-500'"      wire:click.prevent="chooseRate({{$index}},{{$num}})" class="rounded  text-white px-2.5 cursor-pointer" id="rate">{{$r}}</button>
</div>
@endforeach
@error('rating') <div class="text-red-400"> {{ $message }} </div>  @enderror

</div>
<div class="p-8 flex flex-nowrap gap-6 -my-6">
<span class="-mx-2">Lowest</span>
<span class="mx-64">Highest</span>
</div>
<div class="flex flex-nowrap w-2/3 p-6">
<textarea  wire:model.defer="formDetail.{{$num}}.comment" class="border-blue-200 border-2 w-3/4 h-16  focus:border-blue-500 focus:outline-none" name="comment" id="" cols="30" rows="10"></textarea>
</div>
@endforeach
</div>

Alpine组件:

<div class="flex w-full h-screen justify-center items-center">
<div x-data="
{
rating: 0,
hoverRating: 0,
ratings: [{'amount': 3, 'label':'Okay'}, {'amount': 4, 'label':'Good'}, {'amount': 5, 'label':'Great'}],
rate(amount) {
if (this.rating == amount) {
this.rating = 0;
}
else this.rating = amount;
}
}
">
<div class="flex space-x-3">
<template x-for="(value, index) in ratings" :key="index">
<button 
@click="rate(value.amount)" 
@mouseover="hoverRating = value.amount" 
@mouseleave="hoverRating = rating" 
aria-hidden="true" 
class="bg-gray-100 focus:outline-none focus:shadow-outline p-1 w-12 m-0 cursor-pointer" 
:class="{
'text-gray-600': hoverRating == value.amount,
'text-red-400': rating == value.amount
}
">
<span x-text="index" />
</button>
</template>
</div>
</div>
</div>

点击这里查看实例

使用@entangle:

与livewire集成
rating: @entangle('rateProperty')

不使用blade循环显示按钮,而是将评级作为Json提供给alpine组件,如下所示:

ratings: {{ json_encode($ratings) }}

有关缠结的更多信息,请参阅https://laravel-livewire.com/docs/2.x/alpine-js

相关内容

  • 没有找到相关文章

最新更新