Laravel Livewire:它是什么以及如何在您的 Web 应用程序中使用它

WBOY
发布: 2024-09-12 10:18:04
原创
910 人浏览过

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:它是什么以及如何在您的 Web 应用程序中使用它的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!