skip to Main Content

I make a draft implementation for my reusable input component.
The code below obviously throws an error.

Question is how to pass the $event back to register blade to get or log the value of the input?

register.blade.php

<div>
    <x-input onChange="(value) => {console.log('value', value)}"></x-input>
<div/>

input.blade.php

@props(['onChange' => 'null'])

<input x-on:change="{{ $onChange($event) }}">

2

Answers


  1. Chosen as BEST ANSWER

    I learned we could just achieve this through Alpine.Js dispatch. I don't need to pass onClick props via Laravel component. I just simply use dispatch to listen the event (x-on).

    What I like in this implementation is that,

    • aside of event information, passing of extra data is easy
    • you don't have to use Laravel props and assigned unnecessary props in the tag.

    register.blade.php

    <div>
        <x-input x-on:custom-input="console.log('your values =', $event.target.newValue)"
        ></x-input>
    <div/>
    

    input.blade.php

    <input x-on:change="$dispatch('custom-input', { newValue: $event.target.value })">
    

    you can pass "key" prop to distinguish each component.


  2. A few things here.

    First off, your markup is wrong. You have a the closing slash at the wrong end of the closing div. Should be </div> not <div/>.

    Then you’re using x-on without x-data. Alpine only picks up components with the x-data attribute.

    Finally, events propagate automatically, so you could just listen on the parent instead:

    {{-- register.blade.php --}}
    <div x-data>
        <x-input x-on:change="console.log('value', $event.target.value)" />
    </div>
    
    {{-- input.blade.php --}}
    <input {{ $attributes }}>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search