Laravel Livewire: 정의 및 웹 앱에서 사용하는 방법

WBOY
풀어 주다: 2024-09-12 10:18:04
원래의
947명이 탐색했습니다.

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

위 내용은 Laravel Livewire: 정의 및 웹 앱에서 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!