### LiVue Component PHP Class Example
Source: https://livue-laravel.com/docs/v1/installation
Example of a LiVue component's PHP class, defining its state and actions. This class extends LiVue\Component.
```php
count++;
}
}
```
--------------------------------
### Define and register a custom LiVue plugin
Source: https://livue-laravel.com/docs/v1/extend
Shows the structure of a LiVue plugin using the install method and how to register it. Plugins allow for bundling hooks, composables, and setup callbacks into reusable units.
```javascript
const MyPlugin = {
name: 'my-plugin', // optional — used for dedup and opt-out
install(api, options, runtime) {
// ...
}
};
LiVue.use(MyPlugin, { /* options */ });
```
--------------------------------
### LiVue Component Blade Template Example
Source: https://livue-laravel.com/docs/v1/installation
Example of a LiVue component's Blade template, using Vue directives for reactivity. This template defines the component's UI.
```blade
Count: {{ count }}
```
--------------------------------
### Configure Plugins and Services in LiVue
Source: https://livue-laravel.com/docs/v1/extend
Demonstrates how to register custom plugins, remove built-in ones, and expose composables or directives globally. This setup is typically performed in the application entry point.
```javascript
import LiVue from 'livue';
// Disable a built-in plugin
LiVue.removePlugin('livue:devtools');
// Register a custom plugin
LiVue.use({
name: 'my-plugin',
install(api, options) {
api.hook('component.init', ({ component }) => {
console.log('init:', component.name);
});
api.composable('myService', reactive({ count: 0 }));
api.directive('highlight', {
mounted(el, binding) {
el.style.background = binding.value || 'yellow';
}
});
api.setup((app) => {
app.config.globalProperties.$prefix = options.prefix;
});
}
}, { prefix: 'APP' });
```
--------------------------------
### Complete LiVue Layout Example in Blade
Source: https://livue-laravel.com/docs/v1/rendering
This example demonstrates a recommended layout structure incorporating various LiVue Blade directives for comprehensive asset and head element management.
```blade
@livueHead
@livueStyles
@vite(['resources/css/app.css', 'resources/js/app.js'])
{{ $slot }}
@livueScripts
```
--------------------------------
### Register Vue plugins and components with LiVue.setup
Source: https://livue-laravel.com/docs/v1/extend
Demonstrates how to hook into the Vue app creation process to register global plugins, components, and directives. This setup is cumulative and applies to all Vue apps created by LiVue.
```javascript
import LiVue from 'livue';
import { createVuetify } from 'vuetify';
import MyButton from './components/MyButton.vue';
const vuetify = createVuetify({ /* ... */ });
LiVue.setup((app) => {
app.use(vuetify);
app.component('MyButton', MyButton);
app.directive('focus', focusDirective);
});
```
```javascript
LiVue.setup((app) => {
// Register a Vue plugin
app.use(MyPlugin, { option: 'value' });
// Register a global Vue component
app.component('my-button', MyButton);
// Register a global directive
app.directive('focus', focusDirective);
});
```
--------------------------------
### Component Communication Example: Dispatch and Listen (PHP)
Source: https://livue-laravel.com/docs/v1/events
Demonstrates a complete example of a page component dispatching an event and another component listening for it. The dispatching component uses `$this->dispatch()` to send an event, and the listening component uses the `#[On]` attribute to handle it. Events are buffered and delivered client-side.
```php
class ModalTest extends Component
{
public string $message = 'Click to open.';
public function openModal()
{
$this->dispatch(
'open-modal',
['title' => 'From Server!']
);
}
}
class Modal extends Component
{
public bool $show = false;
public string $modalTitle = '';
#[On('open-modal')]
public function open(array $data = [])
{
$this->show = true;
$this->modalTitle = $data['title'];
}
}
```
--------------------------------
### Install LiVue Package (PHP)
Source: https://livue-laravel.com/docs/v1/installation
Installs the LiVue package into your Laravel project using Composer. This is a required step for using LiVue.
```bash
composer require livue/livue
```
--------------------------------
### Basic LiVue Setup in Vue
Source: https://livue-laravel.com/docs/v1/javascript
Initializes LiVue by providing a callback function to LiVue.setup(). This callback receives the Vue app instance, allowing for custom configurations like plugin registration. It's essential for setting up LiVue in your application's main JavaScript file.
```javascript
import LiVue from 'livue';
LiVue.setup((app) => {
// app is a Vue app instance (from createApp())
// Configure it however you need
});
```
--------------------------------
### Blade Setup for LiVue Styles and Scripts (Blade)
Source: https://livue-laravel.com/docs/v1/installation
Includes LiVue's CSS and JavaScript runtime in your Blade layout. This is optional if automatic asset injection is enabled.
```blade
@livueStyles
@livueHead
{{ $slot }}
@livueScripts
```
--------------------------------
### Initialize LiVue with Vite (JavaScript)
Source: https://livue-laravel.com/docs/v1/installation
Initializes LiVue in your application's JavaScript entry point. This is necessary for Vite integration and HMR.
```javascript
import LiVue from 'livue';
LiVue.start();
```
--------------------------------
### Create a Reactive Counter Component with LiVue
Source: https://livue-laravel.com/docs
This example demonstrates how to define a server-side component with reactive state and methods, and how to bind those to a Blade template using Vue directives.
```php
namespace App\LiVue;
use LiVue\Component;
class Counter extends Component
{
public int $count = 0;
public function increment()
{
$this->count++;
}
public function decrement()
{
$this->count--;
}
}
```
```blade
{{ count }}
```
--------------------------------
### LiVue Component Setup with UsePagination Trait (PHP)
Source: https://livue-laravel.com/docs/v1/pagination
Demonstrates how to set up a LiVue component to use the `UsePagination` trait. This trait adds pagination capabilities, including page tracking, URL synchronization, and exposing reactive pagination metadata to the Vue template.
```php
version('2.4.0');
Js::make('tables-js', url('primix/tables.js'))
->version('2.4.0')
->onRequest();
// Example output:
// /livue/livue.js?v=3.1.0
```
--------------------------------
### Publish LiVue Static Assets (PHP)
Source: https://livue-laravel.com/docs/v1/installation
Publishes LiVue's static assets to the public directory. This is optional and typically only needed for custom deployment strategies.
```bash
php artisan vendor:publish --tag=livue-assets
```
--------------------------------
### Access LiVue Components from JavaScript
Source: https://livue-laravel.com/docs/v1/extend
Demonstrates how to access mounted LiVue components using LiVue's JavaScript API. Includes methods for getting the first component, all components, finding by ID, and finding by name. Returns component details including id, name, state, and livue instance.
```javascript
const component = LiVue.first();
const components = LiVue.all();
const component = LiVue.find('livue-123abc');
const counters = LiVue.getByName('counter');
```
--------------------------------
### Configure Vite for Vue Full Build (JavaScript)
Source: https://livue-laravel.com/docs/v1/installation
Configures Vite to use the Vue full build, which is required for LiVue to compile templates in the browser. This includes setting up the 'vue' alias.
```javascript
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
resolve: {
alias: {
'vue': 'vue/dist/vue.esm-bundler.js',
},
},
plugins: [
laravel({
input: ['resources/js/app.js'],
refresh: true,
}),
tailwindcss(),
],
});
```
--------------------------------
### Quick Pinia Stores with useStore() and livue.sync()
Source: https://livue-laravel.com/docs/v1/javascript
Access and synchronize Pinia stores declared in PHP directly within Vue components. Use `useStore(name)` to get a store instance and `livue.sync()` to persist frontend changes to the backend.
```javascript
const componentStore = useStore('demo-counter');
const globalStore = livue.useGlobalStore('demo-global-counter');
// Frontend updates (local until sync)
componentStore.count++;
globalStore.count++;
const syncToBackend = () => livue.sync();
```
--------------------------------
### Register Additional Component Namespaces (PHP)
Source: https://livue-laravel.com/docs/v1/installation
This code snippet demonstrates how to register extra component namespaces for Livue, typically used for modules or packages. This is done within the `boot` method of a service provider.
```php
use LiVue\Facades\LiVue;
public function boot(): void
{
LiVue::registerNamespace([
'App\\Admin\\LiVue',
'App\\Billing\\LiVue',
]);
}
```
--------------------------------
### Configure Livue Assets, Routes, and Components (PHP)
Source: https://livue-laravel.com/docs/v1/installation
This configuration file defines key settings for the Livue package in Laravel. It controls automatic asset injection, the URL prefix for AJAX endpoints, middleware, the namespace and path for component discovery, and the default Blade layout for page components.
```php
return [
// Auto-inject CSS and JS when components are detected
'inject_assets' => true,
// URL prefix for AJAX endpoints
'route_prefix' => 'livue',
// Middleware applied to AJAX endpoints
'middleware' => ['web'],
// Namespace for auto-discovery of components
'component_namespace' => 'App\\LiVue',
// Filesystem path where components live
'component_path' => app_path('LiVue'),
// Default layout for page components
'layout' => 'components.layouts.app',
];
```
--------------------------------
### Trigger Background File Download in Template
Source: https://livue-laravel.com/docs/v1/features
Demonstrates how to trigger a file download action from a Vue template. The process uses an encrypted token and a background GET request to prevent UI blocking.
```html
```
--------------------------------
### Implement Lazy Loading Components
Source: https://livue-laravel.com/docs/v1/components
Lazy-loaded components defer execution of the mount() method until the component enters the viewport. This example shows the component class and the associated skeleton placeholder view.
```php
use LiVue\Attributes\Lazy;
#[Lazy]
class LazyChart extends Component
{
public array $data = [];
public function placeholder(): string
{
return 'livue.chart-skeleton';
}
public function mount(): void
{
$this->data = DB::table('analytics')
->selectRaw('DATE(created_at) as date, COUNT(*) as count')
->groupBy('date')
->get()->toArray();
}
protected function render(): string
{
return 'livue.lazy-chart';
}
}
```
```html
Loading chart...
```
--------------------------------
### Registering Global Vue Directives with LiVue
Source: https://livue-laravel.com/docs/v1/javascript
Shows how to register custom global directives in Vue using LiVue.setup(). The example includes a 'focus' directive to automatically focus an element and a 'tooltip' directive to display a tooltip. These directives can be applied to any HTML element in your Vue components.
```javascript
import LiVue from 'livue';
LiVue.setup((app) => {
app.directive('focus', {
mounted(el) {
el.focus();
}
});
app.directive('tooltip', {
mounted(el, binding) {
el.title = binding.value;
},
updated(el, binding) {
el.title = binding.value;
}
});
});
```
--------------------------------
### Integrating Vuetify with LiVue
Source: https://livue-laravel.com/docs/v1/javascript
Demonstrates how to integrate the Vuetify UI framework with LiVue. Vuetify is installed and configured with a theme, then registered as a Vue plugin using LiVue.setup(). This allows you to use Vuetify components and styles within your LiVue-powered Vue applications.
```javascript
import LiVue from 'livue';
import { createVuetify } from 'vuetify';
import 'vuetify/styles';
const vuetify = createVuetify({
theme: {
defaultTheme: 'dark'
}
});
LiVue.setup((app) => {
app.use(vuetify);
});
```
--------------------------------
### LiVue Component Testing: Contact Form Example
Source: https://livue-laravel.com/docs/v1/development
A comprehensive example of testing a contact form component using LiVue's server-side testing utilities. It covers validation assertions, setting multiple properties, submitting the form, and checking for dispatched events and redirects.
```php
use App\LiVue\ContactForm;
use App\LiVue\Login; // Assuming Login component exists
use LiVue\Facades\LiVue;
describe('ContactForm', function () {
it('validates required fields', function () {
LiVue::test(ContactForm::class)
->call('submit')
->assertHasErrors(['name', 'email', 'message']);
});
it('validates email format', function () {
LiVue::test(ContactForm::class)
->set('name', 'John')
->set('email', 'not-an-email')
->set('message', 'Hello')
->call('submit')
->assertHasErrors('email')
->assertHasNoErrors(['name', 'message']);
});
it('submits a valid form', function () {
LiVue::test(ContactForm::class)
->set([
'name' => 'John Doe',
'email' => 'john@example.com',
'message' => 'Hello World',
])
->call('submit')
->assertHasNoErrors()
->assertDispatched('form-submitted')
->assertSee('Thank you for your message!');
});
it('redirects after login', function () {
LiVue::test(Login::class)
->set('email', 'admin@example.com')
->set('password', 'password')
->call('login')
->assertRedirect('/dashboard');
});
});
```
--------------------------------
### Defining Advanced Pinia Store (Vue/JavaScript)
Source: https://livue-laravel.com/docs/v1/javascript
Provides an example of defining a more advanced Pinia store using `defineStore` in a separate JavaScript file. This store, named 'cart', manages an array of items. This pattern is useful for organizing complex state management logic.
```javascript
import { defineStore } from 'pinia';
export const useCartStore = defineStore('cart', {
state: () => ({ items: [] }),
});
```
--------------------------------
### Manage Lifecycle Hooks
Source: https://livue-laravel.com/docs/v1/extend
Utilize LiVue.hook to monitor component and request lifecycles. Includes examples for cleanup registration and unsubscribing from events.
```javascript
LiVue.hook('component.init', ({ component, el, cleanup }) => {
console.log('Component initialized:', component.name);
cleanup(() => {
console.log('Component cleaned up');
});
});
LiVue.hook('request.started', ({ url, updateCount }) => {
console.log(`Request to ${url} with ${updateCount} updates`);
});
const unsubscribe = LiVue.hook('request.started', callback);
unsubscribe();
```
--------------------------------
### Registering CSS and JavaScript Assets with LiVueAsset Facade (PHP)
Source: https://livue-laravel.com/docs/v1/development
Register CSS and JavaScript assets from service providers using the LiVueAsset facade. Assets are automatically deduplicated and versioned. This example shows registering global assets.
```php
use LiVue\Facades\LiVueAsset;
use LiVue\Features\SupportAssets\Js;
use LiVue\Features\SupportAssets\Css;
public function boot(): void
{
$this->app->booted(function () {
LiVueAsset::register([
Css::make('my-styles', url('css/custom.css'))->version('1.2.3'),
Js::make('my-script', url('js/custom.js'))->module()->version('1.2.3'),
], 'my-package');
});
}
```
--------------------------------
### LiVue Snapshot State with Inline Tuples (JSON)
Source: https://livue-laravel.com/docs/v1/state
Provides an example of a snapshot state in JSON format, showcasing how LiVue uses inline tuples to represent synthesized PHP types. Each tuple contains the serialized value and metadata, including an 's' key for the synthesizer type. Scalar types are passed through directly.
```json
{
"state": {
"count": 5, // scalar — no tuple
"item": [
{"id": 1, "title": "Buy milk"}, // serialized value
{"s": "mdl", "class": "App\\Models\\ToDo", "key": 1} // metadata
],
"status": ["pending", {"s": "enm", "class": "App\\Enums\\TodoStatus"}],
"dueDate": ["2025-01-27T10:00:00+00:00", {"s": "crb"}],
"tags": [["urgent", "test"], {"s": "clc"}]
}
}
```
--------------------------------
### Configure and Control LiVue Progress Bar
Source: https://livue-laravel.com/docs/v1/extend
Shows how to customize the appearance of the built-in progress bar used for AJAX requests and SPA navigation. Includes configuration options for color and height, as well as manual control to start and stop the progress bar.
```javascript
LiVue.progress.configure({
color: '#29d',
height: '3px',
});
LiVue.progress.start();
LiVue.progress.done();
```
--------------------------------
### Configure Plugins, Components, and Directives
Source: https://livue-laravel.com/docs/v1/javascript
Shows how to use the LiVue.setup() method to register custom plugins, global components, and directives within the application lifecycle.
```javascript
LiVue.setup((app) => {
app.use(MyPlugin, { option: 'value' });
app.component('my-button', MyButton);
app.directive('focus', focusDirective);
});
```
--------------------------------
### Configure Stream Modes via stream() Method
Source: https://livue-laravel.com/docs/v1/features
Illustrates the difference between append mode (default) and replace mode when sending data chunks from the server.
```php
// Append mode (default) - content accumulates
$this->stream(to: 'output', content: 'Hello ');
$this->stream(to: 'output', content: 'World!');
// Result: "Hello World!"
// Replace mode - content is overwritten
$this->stream(to: 'progress', content: '50%', replace: true);
$this->stream(to: 'progress', content: '100%', replace: true);
// Result: "100%"
```
--------------------------------
### Publish LiVue Configuration (PHP)
Source: https://livue-laravel.com/docs/v1/installation
Publishes the LiVue configuration file to your Laravel project. This allows for customization of LiVue settings like component paths and middleware.
```bash
php artisan vendor:publish --tag=livue-config
```
--------------------------------
### Render LiVue Component in Blade (Blade)
Source: https://livue-laravel.com/docs/v1/installation
Renders a LiVue component within a Blade view using the @livue directive. This directive accepts the component's name as an argument.
```blade
@livue('counter')
```
--------------------------------
### Generate LiVue Component (PHP)
Source: https://livue-laravel.com/docs/v1/installation
Generates a new LiVue component using an Artisan command. This creates the PHP class for the component's logic and the Blade template for its structure.
```bash
php artisan make:livue Counter
```
--------------------------------
### Trigger File Downloads from Server-Side
Source: https://livue-laravel.com/docs/v1/features
Use the download() method to serve existing files from local or cloud storage, or downloadContent() to trigger downloads for dynamically generated data.
```php
public function downloadReport(): void
{
$this->download(storage_path('reports/monthly.pdf'), 'report.pdf');
}
public function downloadInvoice(int $id): void
{
$invoice = Invoice::findOrFail($id);
$this->download(
path: $invoice->file_path,
name: "invoice-{$invoice->number}.pdf",
disk: 's3'
);
}
public function exportCsv(): void
{
$users = User::all();
$csv = "Name,Email\n";
foreach ($users as $user) {
$csv .= "{$user->name},{$user->email}\n";
}
$this->downloadContent($csv, 'users.csv', [
'Content-Type' => 'text/csv',
]);
}
```
--------------------------------
### Define Component Props and Reactivity
Source: https://livue-laravel.com/docs/v1/components
Shows how to receive props via the mount method and how to use the Reactive attribute for automatic state synchronization.
```php
class ChildComponent extends Component
{
public array $items = [];
public string $title = '';
public function mount(array $items = [], string $title = ''): void
{
$this->items = $items;
$this->title = $title;
}
}
```
```php
use LiVue\Attributes\Reactive;
class ItemList extends Component
{
#[Reactive]
public array $items = [];
}
```
--------------------------------
### Register Vue Plugins with LiVue
Source: https://livue-laravel.com/docs/v1/javascript
Demonstrates how to register Vue plugins like Vuetify or i18n using LiVue.setup(). Calls are cumulative, allowing for modular configuration across different parts of the application.
```javascript
import LiVue from 'livue';
import { createVuetify } from 'vuetify';
import { createI18n } from 'vue-i18n';
const vuetify = createVuetify({ /* ... */ });
const i18n = createI18n({ /* ... */ });
// Register multiple plugins in one call
LiVue.setup((app) => {
app.use(vuetify);
app.use(i18n);
});
// Or spread across multiple setup() calls
LiVue.setup((app) => {
app.use(vuetify);
});
LiVue.setup((app) => {
app.use(i18n);
});
```
--------------------------------
### LiVue Property Attribute Example (Trim)
Source: https://livue-laravel.com/docs/v1/extend
A PHP example demonstrating a custom LiVue property attribute named 'Trim'. This attribute automatically trims whitespace from string property values during the hydration process before validation.
```php
namespace App\LiVue\Attributes;
use Attribute;
use LiVue\Features\SupportAttributes\Attribute as LiVueAttribute;
#[Attribute(Attribute::TARGET_PROPERTY)]
class Trim extends LiVueAttribute
{
public function hydrate(): void
{
$value = $this->getValue();
if (is_string($value)) {
$this->setValue(trim($value));
}
}
}
```
--------------------------------
### Accessing Pinia Stores in LiVue Components
Source: https://livue-laravel.com/docs/v1/javascript
Illustrates how to access and interact with Pinia stores within LiVue components using JavaScript. It shows how to use `useStore` for component-level stores and `livue.useGlobalStore` for global stores defined either at bootstrap or within the component. State updates are demonstrated.
```javascript
const componentStore = useStore('demo-counter');
const globalStore = livue.useGlobalStore('demo-global-counter');
const appGlobalStore = livue.useGlobalStore('demo-app-counter');
componentStore.count++;
globalStore.count++;
appGlobalStore.count++;
```
--------------------------------
### LiVue Method Attribute Example (LogCall)
Source: https://livue-laravel.com/docs/v1/extend
A PHP example of a custom LiVue method attribute named 'LogCall'. This attribute logs the component name, method name, and call parameters whenever the target method is invoked.
```php
#[Attribute(Attribute::TARGET_METHOD)]
class LogCall extends LiVueAttribute
{
public function call(array $params): void
{
$component = $this->getComponent();
\Log::info("LiVue: {$component->getName()}::{$this->getName()}", $params);
}
}
```
--------------------------------
### LiVue Pagination Vue Composable Example (Vue)
Source: https://livue-laravel.com/docs/v1/attributes
Shows how to access and use pagination data and actions within a Vue template when the UsePagination trait is registered as a composable. Provides examples for navigation buttons and displaying page information.
```vue
Page {{ pagination.page }} of {{ pagination.lastPage }}
```
--------------------------------
### Manual Paginator Management with setPaginator
Source: https://livue-laravel.com/docs/v1/pagination
Shows how to manually set a paginator instance within a component's render method, which is useful when query logic is handled outside of the template.
```php
class ProductCatalog extends Component
{
use UsePagination;
protected array $composables = ['usePagination'];
public string $category = 'all';
public function render(): string
{
$query = Product::query();
if ($this->category !== 'all') {
$query->where('category', $this->category);
}
$this->setPaginator(
$query->paginate(12)
);
return 'livue.product-catalog';
}
}
```
--------------------------------
### LiVue v-init: Initial Data Loading
Source: https://livue-laravel.com/docs/v1/directives
Call a server method when the component is first mounted. Ideal for deferred data loading where the initial HTML renders instantly and data is fetched asynchronously. Can be combined with v-loading for a seamless user experience.
```html
Loading...
{{ item.name }}
```
--------------------------------
### Quick Store Pattern in @script
Source: https://livue-laravel.com/docs/v1/rendering
Illustrates consuming component and global stores within the @script directive. It shows how to access and modify store states and synchronize changes to the backend using the livue helper.
```blade
@script
const componentStore = useStore('demo-counter');
const globalStore = livue.useGlobalStore('demo-global-counter');
const appGlobalStore = livue.useGlobalStore('demo-app-counter');
componentStore.count++;
globalStore.count++;
appGlobalStore.count++;
const syncToBackend = () => livue.sync();
return { componentStore, globalStore, appGlobalStore, syncToBackend };
@endscript
```
--------------------------------
### LiVue Layout Blade Template
Source: https://livue-laravel.com/docs/v1/components
Example of a LiVue layout Blade template. It includes the `@livueHead` directive for head management and renders the component's slot using unescaped output.
```blade
{{ $title ?? config('app.name') }}
@livueHead
@vite(['resources/js/app.js'])
{!! $slot !!}
```
--------------------------------
### Execute Background Streaming
Source: https://livue-laravel.com/docs/v1/features
Demonstrates how to trigger a stream without automatically applying the final response, allowing for custom event handling via livue:stream-complete.
```html
```
--------------------------------
### Implement Global Error Handling
Source: https://livue-laravel.com/docs/v1/javascript
Provides examples for intercepting application-wide errors using LiVue.onError(). This includes basic logging and advanced integrations like toast notifications and Sentry error tracking.
```javascript
import LiVue from 'livue';
import { toast } from 'vue-sonner';
LiVue.onError((error, componentName) => {
// Show toast to the user
toast.error('Something went wrong. Please try again.');
// Send to error tracking service
Sentry.captureException(error, {
tags: { component: componentName }
});
});
```
--------------------------------
### Define LiVue Component Lifecycle Hooks
Source: https://livue-laravel.com/docs/v1/lifecycle
Demonstrates how to implement core lifecycle methods such as boot, mount, hydrate, and property-specific update hooks within a LiVue component class.
```php
class UserEditor extends Component
{
public string $name = '';
public string $email = '';
public function boot(): void
{
// Runs on every request
}
public function mount(User $user): void
{
$this->name = $user->name;
$this->email = $user->email;
}
public function hydrate(): void
{
// Rebuild non-serializable objects
$this->service = app(MyService::class);
}
public function updatingEmail(string $value): string
{
// Normalize before setting
return strtolower(trim($value));
}
public function updatedEmail(string $value): void
{
// React after the value changed
$this->checkAvailability($value);
}
public function dehydrate(): void
{
// Cleanup before serialization
unset($this->temporaryData);
}
}
```
--------------------------------
### Monitor Network Requests with LiVue Hooks
Source: https://livue-laravel.com/docs/v1/javascript
Shows how to track request start and finish events to calculate performance metrics. It utilizes closure variables to measure the duration between request initiation and completion.
```javascript
let requestStart;
LiVue.hook('request.started', ({ url, updateCount }) => {
requestStart = performance.now();
console.log(`Request to ${url} with ${updateCount} updates`);
});
LiVue.hook('request.finished', ({ url, success, error }) => {
const duration = performance.now() - requestStart;
if (success) {
console.log(`Request completed in ${duration.toFixed(0)}ms`);
} else {
console.error('Request failed:', error);
}
});
```
--------------------------------
### Registering JavaScript and CSS Assets
Source: https://livue-laravel.com/docs/v1/development
Demonstrates how to register standard, module, inline, and versioned JavaScript and CSS assets using the Js and Css facade classes.
```php
// JavaScript Assets
Js::make('id', '/path/to/script.js');
Js::make('id', '/path/to/module.js')->module();
Js::make('id', '')->inline('console.log("hi")');
Js::make('id', '/path.js')->async();
Js::make('id', '/path.js')->version('1.2.3');
// CSS Assets
Css::make('id', '/path/to/styles.css');
Css::make('id', '/path/to/print.css')->media('print');
Css::make('id', '')->inline('.my-class { color: red; }');
Css::make('id', '/path/to/styles.css')->version('1.2.3');
```
--------------------------------
### LiVue Method Attribute Usage (LogCall)
Source: https://livue-laravel.com/docs/v1/extend
Example of applying the 'LogCall' method attribute to a method within a LiVue component. The `#[LogCall]` attribute ensures that calls to the `deleteUser` method are logged with relevant information.
```php
class AdminPanel extends Component
{
#[LogCall]
public function deleteUser(int $id): void { /* ... */ }
}
```
--------------------------------
### Create Trait-Based Lifecycle Hooks
Source: https://livue-laravel.com/docs/v1/lifecycle
Illustrates how to encapsulate reusable logic in traits using the {hook}{TraitName} naming pattern, which executes automatically alongside component hooks.
```php
trait WithSearch
{
public string $search = '';
public function bootWithSearch(): void
{
// Called during boot()
}
public function mountWithSearch(): void
{
$this->search = request()->query('q', '');
}
public function hydrateWithSearch(): void
{
// Called during hydrate()
}
}
// Usage
class ProductList extends Component
{
use WithSearch;
}
```
--------------------------------
### LiVue Pagination Configuration (PHP)
Source: https://livue-laravel.com/docs/v1/pagination
Shows the configuration for LiVue's pagination views. The `pagination` key in `config/livue.php` allows you to specify which view to use for rendering pagination links, supporting default, simple, or custom views.
```php
'pagination' => 'default',
```
--------------------------------
### Global Component Finding with LiVue API
Source: https://livue-laravel.com/docs/v1/javascript
Utilize the global `LiVue` object to find and interact with component instances. Methods include finding by ID, getting the first or all components, and finding components by their registered name.
```javascript
// Get the first component on the page
const component = LiVue.first();
// Get all root/island components
const components = LiVue.all();
console.log('Found', components.length, 'components');
// Find a specific component by ID
const cart = LiVue.find('livue-abc123');
console.log(cart.state);
// Find all components by name
const counters = LiVue.getByName('counter');
// Returns: [{ id, name, state, livue }, ...]
```
--------------------------------
### Test LiVue Component Lifecycle Server-Side
Source: https://livue-laravel.com/docs/v1/development
Demonstrates how to use `LiVue::test()` to instantiate and mount LiVue components for server-side testing. The `Testable` instance provides chainable methods for interaction and assertions, simulating the full component lifecycle without a browser.
```php
use App\LiVue\Counter;
use LiVue\Facades\LiVue;
it('starts at zero', function () {
LiVue::test(Counter::class)
->assertSet('count', 0)
->assertSee('0');
});
it('increments the counter', function () {
LiVue::test(Counter::class)
->call('increment')
->assertSet('count', 1);
});
it('can set properties', function () {
LiVue::test(Counter::class)
->set('count', 10)
->call('increment')
->assertSet('count', 11);
});
// With mount parameters
LiVue::test(UserProfile::class, ['userId' => 1])
->assertSet('user.name', 'John Doe')
->assertSee('John Doe');
```
--------------------------------
### Vite Alias Configuration for LiVue
Source: https://livue-laravel.com/docs/v1/javascript
Configures a Vite alias to correctly import LiVue from its distributed ESM file. This is necessary because LiVue is installed via Composer, not npm. The alias ensures that 'livue' can be imported cleanly in your JavaScript files.
```javascript
import { defineConfig } from 'vite';
import { resolve } from 'path';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
resolve: {
alias: {
'livue': resolve(__dirname, 'vendor/livue/livue/dist/livue.esm.js'),
},
},
plugins: [
laravel({
input: ['resources/css/app.css', 'resources/js/app.js'],
refresh: true,
}),
],
});
```
--------------------------------
### Registering Lifecycle Event Listeners
Source: https://livue-laravel.com/docs/v1/lifecycle
Demonstrates how to register lifecycle event listeners using static methods within a Laravel ServiceProvider's boot method.
```php
use App\LiVue\Counter;
// In a ServiceProvider::boot()
Counter::mounting(function ($component) {
Log::info("Counter is about to mount");
});
Counter::mounted(function ($component) {
Log::info("Counter mounted, count = {$component->count}");
});
Counter::calling(function ($component, $method, $params) {
Log::info("Calling {$method} on Counter");
});
```
--------------------------------
### Implement Property-Specific Hooks
Source: https://livue-laravel.com/docs/v1/lifecycle
Shows how to define hooks that trigger specifically when a named property is updated, using PascalCase naming conventions.
```php
public string $search = '';
public array $items = [];
// Called before $search is updated
public function updatingSearch(string $value): string
{
return trim($value);
}
// Called after $search is updated
public function updatedSearch(string $value): void
{
$this->resetPage();
}
// Array properties also receive the key
public function updatedItems(mixed $value, ?string $key): void
{
if ($key !== null) {
// Specific item changed
}
}
```
--------------------------------
### LiVue Property Attribute Usage (Clamp)
Source: https://livue-laravel.com/docs/v1/extend
Example demonstrating the usage of the 'Clamp' property attribute in a LiVue component. The `#[Clamp(min: 0, max: 255)]` attribute is applied to the `$brightness` property, enforcing the specified bounds.
```php
class Slider extends Component
{
#[Clamp(min: 0, max: 255)]
public int $brightness = 128;
}
```
--------------------------------
### Create and Edit Resources with Form Objects
Source: https://livue-laravel.com/docs/v1/state
Shows how to reuse a single Form Object for both creating new records and updating existing ones by leveraging the fill method and conditional logic.
```php
class PostForm extends Form
{
public ?Post $post = null;
#[Validate('required|min:5')]
public string $title = '';
#[Validate('required')]
public string $content = '';
public function setPost(Post $post): static
{
$this->post = $post;
$this->fill($post);
return $this;
}
public function save(): Post
{
$validated = $this->validate();
if ($this->post) {
$this->post->update($validated);
return $this->post;
}
$post = Post::create($validated);
$this->reset();
return $post;
}
}
```
--------------------------------
### Initialize Laravel Echo for Broadcasting (JavaScript)
Source: https://livue-laravel.com/docs/v1/events
Set up Laravel Echo in your application's JavaScript before LiVue boots. This requires importing Echo and Pusher, configuring the broadcaster, key, cluster, and TLS settings. Ensure this script runs before `@livueScripts`.
```javascript
import Echo from 'laravel-echo';
import Pusher from 'pusher-js';
window.Pusher = Pusher;
window.Echo = new Echo({
broadcaster: 'pusher',
key: import.meta.env.VITE_PUSHER_APP_KEY,
cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER,
forceTLS: true,
});
```