Skip to content

wire:submit

Livewire 通过 wire:submit 指令让处理表单提交变得非常简单。通过将 wire:submit 添加到 <form> 元素,Livewire 将拦截表单提交,阻止浏览器的默认处理,并调用任何 Livewire 组件方法。

这是一个使用 wire:submit 处理"创建文章"表单提交的基本示例:

php
<?php

namespace App\Livewire;

use Livewire\Component;
use App\Models\Post;

class CreatePost extends Component
{
    public $title = '';

    public $content = '';

    public function save()
    {
        Post::create([
            'title' => $this->title,
            'content' => $this->content,
        ]);

        $this->redirect('/posts');
    }

    public function render()
    {
        return view('livewire.create-post');
    }
}
blade
<form wire:submit="save">
    <input type="text" wire:model="title">

    <textarea wire:model="content"></textarea>

    <button type="submit">Save</button>
</form>

在上面的示例中,当用户通过点击"Save"提交表单时,wire:submit 拦截 submit 事件并在服务器上调用 save() 操作。

Livewire 自动调用 preventDefault()

wire:submit 与其他 Livewire 事件处理器不同,它内部会调用 event.preventDefault(),无需使用 .prevent 修饰符。这是因为在极少数情况下,你监听 submit 事件时会不想阻止其默认的浏览器处理(执行完整的表单提交到端点)。

Livewire 自动禁用提交中的表单

默认情况下,当 Livewire 向服务器发送表单提交时,它会禁用表单提交按钮并将所有表单输入标记为 readonly。这样用户在初始提交完成之前无法再次提交同一表单。

深入了解

wire:submit 只是 Livewire 提供的众多事件监听器之一。以下两个页面提供了关于在应用程序中使用 wire:submit 的更完整文档:

另请参阅

  • 表单 — 使用 Livewire 处理表单提交
  • 操作 — 在操作中处理表单数据
  • 验证 — 提交前验证表单

参考

blade
wire:submit="methodName"
wire:submit="methodName(param1, param2)"

修饰符

修饰符描述
.prevent阻止默认浏览器行为(wire:submit 自动应用)
.stop停止事件传播
.self仅当事件源自此元素时触发
.once确保监听器只被调用一次
.debounce防抖处理器 250ms(使用 .debounce.500ms 自定义时长)
.throttle节流处理器至少每 250ms 一次(使用 .throttle.500ms 自定义)
.windowwindow 对象上监听事件
.documentdocument 对象上监听事件
.passive不会阻塞滚动性能
.capture在捕获阶段监听
.renderless操作完成后跳过重新渲染
.preserve-scroll更新期间保持滚动位置
.async并行执行操作而非排队