Maison  >  Article  >  développement back-end  >  Laravel Livewire : qu'est-ce que c'est et comment l'utiliser dans votre application Web

Laravel Livewire : qu'est-ce que c'est et comment l'utiliser dans votre application Web

WBOY
WBOYoriginal
2024-09-12 10:18:04912parcourir

Livewire 是 Laravel 生態系統中最重要的專案之一,專門針對前端開發。 Livewire v3 最近發布了,讓我們來探討一下 Livewire 是什麼,以及什麼樣的專案適合它的架構。

Livewire 的獨特之處在於它允許開發「現代」Web 應用程序,而無需使用專用的 JavaScript 框架。

使用 Livewire,可以開發提供與 Vue 或 React 相同程度的反應性的 Blade 元件,而無需透過解耦的前端和後端來管理專案的複雜性。 您可以在 Laravel 和 Blade 模板的範圍內繼續開發您的應用程式。

Livewire 的工作原理

Livewire 是一個 Composer 套件,您可以將其新增至 Laravel 專案中。然後必須使用適當的 Blade 指令在每個 HTML 頁面(或該頁面,如果您想要建立單頁面應用程式)上啟動它。 Livewire 元件由 PHP 類別和 Blade 檔案組成,其中包含特定前端元件如何運作以及必須呈現的邏輯。

當瀏覽器要求存取使用 Livewire 的頁面時,會發生以下情況:

  • 頁面以元件的初始狀態呈現,就像使用 Blade 建立的任何頁面一樣;
  • 當元件 UI 觸發交互時,將對適當的路由進行 AJAX 調用,指示 Livewire 元件和發生的交互,以及元件的狀態;
  • 資料在組件的 PHP 部分進行處理,該部分執行交互結果的新渲染並將其發送回瀏覽器;
  • 頁面的 DOM 根據從伺服器收到的變更而變更。

它與 Vue 和 React 的做法非常相似,但在這種情況下,回應互動的反應性邏輯由後端管理,而不是在 javascript 端管理。

為了幫助您更好地理解邏輯,我將在下面向您展示此比較的範例。

如果您想了解更多有關建立開發人員驅動的公司所面臨的挑戰,您可以在 Linkedin 或 X 上關注我。

如何安裝 Laravel Livewire

Livewire 安裝絕對是最少的。在 Laravel 專案中安裝 Composer 套件,並將必要的 Blade 指令新增至所有頁面(或專案中所有 Blade 範本所衍生的通用佈局)。

composer require livewire/livewire
<html>
<head>
    ...

    @livewireStyles
</head>
<body>
    ...

    @livewireScripts
</body>
</html>

如何建立 Laravel Livewire 元件

安裝 Composer 套件後,可以使用新的 Artisan make 子指令來建立新的 Livewire 元件。每個元件將由一個 PHP 類別和一個 Blade 視圖組成。

它類似於 Blade 基於類別的元件。

php artisan make:livewire SpyInput    
COMPONENT CREATED ?

CLASS: app/Http/Livewire/SpyInput.php
VIEW: resources/views/livewire/spy-input.blade.php

此範例中的元件將「監視」HTML 輸入欄位中寫入的內容,而無需編寫 JavaScript 程式碼。

然後我們將公共屬性插入到元件類別中:

// app/Http/Livewire/SpyInput.php

namespace App\Livewire;

use Livewire\Component;

class SpyInput extends Component
{
    public string $message;

    public function render()
    {
        return view('livewire.spy-input');
    }
}

實作元件視圖如下:

// resources/views/livewire/spy-input.blade.php

<div>
    <label>Type here:</label>
    <input type="text" wire:model="message"/>
    <span>You typed: <span>{{ $message }}</span></span>
</div>

最後將 Livewire 元件放入刀片視圖:

<html>
<head>
    @livewireStyles
</head>
<body>

    <livewire:spy-input />

    @livewireScripts
</body>
</html>

在普通的 Blade 元件中,元件類別的所有公共屬性在 Blade 模板中都是可見的。所以在 {{ $message }}$message 屬性的值會自動顯示。然而,在普通的基於類別的元件中,這只發生在第一個元件渲染時。如果您在輸入欄位中輸入內容,span 標記中不會發生任何變更。

但是,在Livewire 元件中,我們在欄位中使用了wire:model="message" 屬性。此屬性確保輸入欄位的值連結到 PHP 類別中的 $message 屬性。當您在輸入欄位中寫入新值時,它將發送到伺服器,伺服器更新$message 的值並執行新的渲染,將其發送回前端,然後更新{{ 中的文字$message }} .

透過開啟瀏覽器開發工具的「網路」選項卡,我們會注意到鍵盤上的每個按鍵都會按以下路線呼叫伺服器:

/livewire/message/<COMPONENT-NAME>

對每個呼叫的回應都包含元件的新渲染 HTML,Livewire 會將其插入到頁面中取代舊的 HTML。可以使用各種自訂導線屬性。例如,您可以在按一下按鈕時執行元件類別的公共方法。以下是此出價的範例:

<button wire:click="doSomething">Click Here</button>
class SpyInput extends Component
{
    public function doSomething()
    {
        // Your code here…
    }
}

其中 doSomething 是 Livewire 元件的 PHP 類別的公共方法。

Integration with other Laravel features

The PHP class connected to the component behaves like any other PHP class in a Laravel project. The only difference is that it uses the mount method instead of the classic __construct class constructor to initialize the public properties of the class.

{{-- Initial assignment of the the $book property in the ShowBook class --}}
<livewire:show-book :book="$book">

class ShowBook extends Component
{
    public $title;
    public $excerpt;

    // "mount" instead of "__constuct"
    public function mount(Book $book = null)
    {
        $this->title = $book->title;
        $this->excerpt = $book->excerpt;
    }
}

You can also use the protected property $rules to configure the validation restrictions on the data sent from the frontend to the backend. You have to call the validate() method to validate the data:

<form wire:submit.prevent="saveBook">
    <input type="text" wire:model="title"/>
    @error('title') <span class="error">{{ $message }}</span> @enderror

    <input type="text" wire:model="excerpt"/>
    @error('excerpt') <span class="error">{{ $message }}</span> @enderror

    <input type="text" wire:model="isbn"/>
    @error('isbn') <span class="error">{{ $message }}</span> @enderror

    <button type="submit">Save Book</button>
</form>
class BookForm extends Component
{
    public $title;
    public $excerpt;
    public $isbn;

    protected $rules = [
        'title' => ['required', 'max:200'],
        'isbn' => ['required', 'unique:books', 'size:17'],
        'excerpt' => 'max:500'
    ];

    public function saveBook()
    {
        $validated = $this->validate($this->rules);

        Book::create($validated);

        return redirect()->to('/books);
    }
}

Or you can use PHP Attributes to declare the desired validation rules for a class property:

class BookForm extends Component
{
    #[Validate('required|max:200')]
    public $title;

    #[Validate('required|unique:books|size:17')]
    public $isbn;

    #[Validate('max:500')]
    public $excerpt;

    public function saveBook()
    {
        $this->validate();

        Book::create([
            'title' => $this->title,
            'isbn' => $this->isbn,
            'excerpt' => $this->excerpt,
        ]);

        return redirect()->to('/books);
    }
}

In general, each Livewire component behaves in the ways that a Laravel developer expects from a PHP class inside a Laravel project. Thus allowing the creation of reactive web interfaces without the need to separate the development projects between Laravel and Vue/React.

Monitor your Laravel application for free

Inspector is a Code Execution Monitoring tool specifically designed for software developers. You don't need to install anything at the server level, just install the Laravel package and you are ready to go.

If you are looking for HTTP monitoring, database query insights, and the ability to forward alerts and notifications into your preferred messaging environment, try Inspector for free. Register your account.

Or learn more on the website: https://inspector.dev

Laravel Livewire: What it is, and how to use it in your web app

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn