分享几个 Laravel 7 中很酷的 Blade 组件

2020-11-01,,

表单按钮

开发一个应用时,如果您希望重定向并且做一些其他操作时,不能使用简单的链接。GET 请求很容易受到 CSRF 攻击。

相反,您应该使用其他 HTTP 请求方式,使用表单和 CSRF 验证。 下面是一个在表单中生成按钮的 FormButton 组件。

{{-- content of formButton.blade.php --}}
<form method="POST" action="{{ $action }}">
    @csrf
    @method($method ?? 'POST')
        <button
            type="submit"
            class="{{ $class ?? '' }}"
        >
            {{ $slot }}
        </button>
</form>

您可以像这样使用它:

// perform an action
<x-form-button :action="route('doSomething')">
   Do something
</x-form-button>
// perform an action with another HTTP verb
<x-form-button :action="route('model.delete', $model)" method="delete">
   Delete model
</x-form-button>

导航栏

几乎任何应用程序都需要显示某种导航,比如菜单和选项卡。这些导航链接是动态的,这样用户就可以知道自己在应用程序的哪个部分。

下面是可以展示链接的 navigationLink 组件。当其以当前请求的 URL 开始时,它会自动将自身设置为活动状态。

{{-- content of navigationLink.blade.php --}}
<li class="{{ \Illuminate\Support\Str::startsWith(request()->url(), $href) ? 'active' : ''  }}">
    <a href="{{ $href }}" @isset($dataDirtyWarn) data-dirty-warn @endisset>
        {{ $slot }}
    </a>
</li>

这里是如何在 mailcoach.app 中使用它的。

 <nav class="tabs">
        <ul>
            <x-navigation-item :href="route('mailcoach.emailLists.subscribers', $emailList)">
                <x-icon-label icon="fa-users" text="Subscribers" :count="$emailList->subscribers()->count() ?? 0" />
            </x-navigation-item>
            <x-navigation-item :href="route('mailcoach.emailLists.tags', $emailList)">
                <x-icon-label icon="fa-tag" text="Tags" />
            </x-navigation-item>
            <x-navigation-item :href="route('mailcoach.emailLists.segments', $emailList)">
                <x-icon-label icon="fa-chart-pie" text="Segments" />
            </x-navigation-item>
            <x-navigation-item :href="route('mailcoach.emailLists.settings', $emailList)">
                <x-icon-label icon="fa-cog" text="Settings" />
            </x-navigation-item>
        </ul>
    </nav>

这就是渲染的方法。

表单元素

Blade 组件会渲染出自适应的表单元素。我们来看一下 textField 组件在 Mailcoach 中的用法。

<div class="form-row">
    @if($label ?? null)
    <label class="{{ ($required ?? false) ? 'label label-required' : 'label' }}" for="{{ $name }}">
        {{ $label }}
    </label>
    @endif
    @error($name)
        <p class="form-error" role="alert">{{ $message }}</p>
    @enderror
    <input
        autocomplete="off"
        type="{{ $type ?? 'text' }}"
        name="{{ $name }}"
        id="{{ $name }}"
        class="input"
        placeholder="{{ $placeholder ?? '' }}"
        value="{{ old($name, $value ?? '') }}"
        {{ ($required ?? false) ? 'required' : '' }}
    >
</div>

正如你所看到的一样,它渲染了标签、表单字段和可能的错误。这就是它的用法。

<x-text-field label="Name" name="name" required />

以上就是分享几个 Laravel 7 中很酷的 Blade 组件的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《分享几个 Laravel 7 中很酷的 Blade 组件.doc》

下载本文的Word格式文档,以方便收藏与打印。