#[Vue]
Execute JavaScript directly in the browser without server round-trips.
Basic Usage
Mark a method with #[Vue] to run JavaScript client-side. The method returns a JS string that gets executed in the browser.
use LiVue\Attributes\Vue;
class TodoForm extends Component
{
public string $title = '';
public string $content = '';
#[Vue]
public function resetForm(): string
{
return <<<'JS'
state.title = '';
state.content = '';
JS;
}
#[Vue]
public function showAlert(): string
{
return <<<'JS'
alert('Title: ' + state.title);
JS;
}
}
Using in Templates
Call Vue methods just like regular methods. They execute instantly without AJAX.
<div>
<input v-model="title" />
<textarea v-model="content"></textarea>
<button @click="livue.call('resetForm')">Reset</button>
<button @click="livue.call('showAlert')">Show Alert</button>
</div>
Available Variables
Inside the JS code, you have access to these variables:
| Variable | Description |
|---|---|
state |
The reactive Vue state (read/write) |
livue |
The LiVue helper (call, set, sync, etc.) |
$el |
The component's root DOM element |
Execute JS After Server Actions
Use $this->vue() to queue JavaScript that runs after a server method completes.
public function save()
{
// Server-side logic
$this->todo->save();
// JS executed after response arrives
$this->vue("alert('Saved successfully!')");
}
public function focusInput()
{
$this->vue("document.querySelector('#my-input').focus()");
}
Calling Server Methods from Vue
Use livue.call() inside your Vue method to trigger server actions.
#[Vue]
public function validateAndSave(): string
{
return <<<'JS'
if (state.title.trim() === '') {
alert('Title is required!');
return;
}
// Proceed with server call
livue.call('save');
JS;
}
When to Use
Good Use Cases
- • Form resets and clearing fields
- • Client-side validation before submit
- • DOM manipulation (focus, scroll)
- • Instant UI feedback (alerts, toasts)
- • Toggle local state
Avoid For
- • Database operations
- • Complex business logic
- • Anything requiring server data
- • State that needs server sync
How It Works
-
1
Method code is collected at render
The PHP method is executed and the returned JS string is stored in the snapshot's
vueMethods. -
2
Client checks for Vue method
When you call
livue.call('method'), the runtime first checksvueMethods. -
3
JS executes locally
If found, the JS runs immediately in the browser. No AJAX request is sent.