英文:
How could I clean up this livewire component?
问题
以下是您要翻译的代码部分:
<div>
<select name="tags[]" id="tags" multiple
class="select2 mt-1 w-full block rounded-md bg-gray-100 border-transparent hover:border-gray-500 hover:bg-white hover:ring-0">
@if (old('tags'))
@foreach (old('tags') as $oldtag)
<option value="{{ $oldtag }}" selected>{{ $oldtag }}</option>
@endforeach
@else
@isset($post)
@if ($post->tags()->count() > 0)
@foreach ($post->tags as $singleTag)
<option value="{{ $singleTag->text }}" selected>{{ $singleTag->text }}</option>
@endforeach
@endif
@endisset
@endif
</select>
@if ($errors->has('tags'))
<small class="text-red-600">{{ $errors->first('tags') }}</small>
@endif
</div>
**select2 script init below inside @push('scripts')**
这是您提供的代码部分的翻译,不包含其他内容。
英文:
The code:
<div>
<select name="tags[]" id="tags" multiple
class="select2 mt-1 w-full block rounded-md bg-gray-100 border-transparent hover:border-gray-500 hover:bg-white hover:ring-0">
@if (old('tags'))
@foreach (old('tags') as $oldtag)
<option value="{{ $oldtag }}" selected>{{ $oldtag }}</option>
@endforeach
@else
@isset($post)
@if ($post->tags()->count() > 0)
@foreach ($post->tags as $singleTag)
<option value="{{ $singleTag->text }}" selected>{{ $singleTag->text }}</option>
@endforeach
@endif
@endisset
@endif
</select>
@if ($errors->has('tags'))
<small class="text-red-600">{{ $errors->first('tags') }}</small>
@endif
</div>
**select2 script init below inside @push('scripts')**
It is a livewire component that takes in an optional parameter named $post
.
The reason I have else-isset-if
is because, if you "edit" a post, the $post
parameter gets that post object but if you "create" a new post, there's no post object to load up in the component. That way laravel still tries to read $post->tags()->count()
which will throw an error stating "null" has no method called tags()
.
That's why I've added the isset
part.
It works but also looks extremely ugly. I have absolutely no idea what to do with it.
答案1
得分: 1
你可能考虑将你的条件逻辑迁移到一个 Livewire 计算属性中:
public function getTagOptionsProperty() {
$old = request()->old('tags');
return $old ?? $this->post->tags()->pluck('text')->toArray();
}
然后,在你的 Blade 视图中:
@foreach($this->tagOptions)
{{-- ... --}}
@endforeach
你的标记似乎混合了 Blade 属性和 Livewire 属性,所以我不太确定这里发生了什么,但似乎有很好的重构机会。
英文:
You might consider migrating your conditional logic into a Livewire computed property instead:
public function getTagOptionsProperty() {
$old = request()->old('tags');
return $old ?? $this->post->tags()->pluck('text')->toArray();
}
Then, inside of your Blade view:
@foreach($this->tagOptions)
{{-- ... --}}
@endforeach
Your markup seems to be mixing Blade attributes with Livewire properties, so I'm not entirely sure what's going on here, but there would seem to be a good opportunity for refactoring.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论