Skip to content
全部文档

Js

#[Js] 属性用于标记返回可在客户端执行的 JavaScript 代码的方法。带有 #[Js] 的方法可直接从模板调用,而无需发起服务器请求。

基本用法

#[Js] 属性应用到返回 JavaScript 表达式的方法上:

php
<?php // resources/views/components/post/⚡create.blade.php

use Livewire\Attributes\Js;
use Livewire\Component;

new class extends Component {
    public $title = '';
    public $content = '';

    #[Js] // [tl! highlight:start]
    public function resetForm()
    {
        return <<<'JS'
            $wire.title = ''
            $wire.content = ''
        JS;
    } // [tl! highlight:end]
};
blade
<form wire:submit="save">
    <input wire:model="title" placeholder="Title">
    <textarea wire:model="content" placeholder="Content"></textarea>

    <button type="submit">Save</button>
    <button type="button" @click="$wire.resetForm()">Reset</button> <!-- [tl! highlight] -->
</form>

调用 $wire.resetForm() 时,JavaScript 直接在浏览器中执行——不会发生服务器往返。

在服务器操作之后执行 JavaScript

若需要在服务器操作完成之后执行 JavaScript,请改用 js() 方法:

php
<?php // resources/views/components/post/⚡create.blade.php

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

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

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

        $this->js("alert('Post saved successfully!')"); // [tl! highlight]
    }
};

js() 方法会排队等待服务器响应到达后再执行 JavaScript。

访问 $wire

你可以在 JavaScript 表达式中访问组件的 $wire 对象:

php
#[Js]
public function resetForm()
{
    return <<<'JS'
        $wire.title = ''
        $wire.content = ''
    JS;
}

何时使用

在以下情况使用 #[Js]

  • 在无服务器开销的情况下重置或清空表单字段
  • 触发 JavaScript 动画或过渡
  • 在不重新渲染的情况下更新客户端状态
  • 从多处执行可复用的 JavaScript 逻辑
  • 与第三方 JavaScript 库集成

JavaScript 操作与 #[Js] 方法

有一个重要区别:

  • #[Js] 方法 在 PHP 中定义并返回 JavaScript 代码。通过 $wire.methodName() 调用,无需服务器请求。
  • JavaScript 操作 ($js.methodName) 完全用 @script 块在 JavaScript 中定义。

两种方式都会在客户端执行 JavaScript,无需服务器往返。区别在于 JavaScript 代码定义的位置。

php
<?php // resources/views/components/⚡example.blade.php

use Livewire\Attributes\Js;
use Livewire\Component;

new class extends Component {
    public $count = 0;

    // JavaScript defined in PHP
    #[Js]
    public function showCount()
    {
        return "alert('Count is: {$this->count}')";
    }
};
blade
<div>
    <button @click="$wire.showCount()">Show Count (from PHP)</button>
    <button @click="$js.incrementLocal()">Increment Local (from JS)</button>
</div>

@script
<script>
    // JavaScript defined in JavaScript
    $js('incrementLocal', () => {
        console.log('No server request made')
    })
</script>
@endscript

了解更多

关于 Livewire 中 JavaScript 集成的更多信息,请参阅: