Skip to content
全部文档

wire:submit

通过 wire:submit 指令,Livewire 可以轻松处理表单提交。在 <form> 上加上 wire:submit 后,Livewire 会拦截提交、阻止浏览器默认行为,并调用任意 Livewire 组件方法。

下面是一个基本示例,用 wire:submit 处理「Create Post」表单提交:

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"> <!-- [tl! highlight] -->
    <input type="text" wire:model="title">

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

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

上例中,用户点击「Save」提交表单时,wire:submit 会拦截 submit 事件,并在服务端调用 save() 动作。

INFO

Livewire 会自动调用 preventDefault()

wire:submit 与其他 Livewire 事件处理不同:它会在内部调用 event.preventDefault(),无需 .prevent 修饰符。因为监听 submit 事件时,几乎总是希望阻止浏览器默认行为(向端点发起完整表单提交)。

INFO

提交期间 Livewire 会自动禁用表单

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

深入了解

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

  • [用 Livewire 响应浏览器事件](/4.x/actions)
  • [在 Livewire 中创建表单](/4.x/forms)

另请参阅

  • Forms — 用 Livewire 处理表单提交
  • Actions — 在动作中处理表单数据
  • Validation — 提交前验证表单

参考

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并行执行动作,而非排队