Alpine JS and Laravel Livewire $wire object, entangle and property synchronization
What is the problem that we currently have that we have to have a reference to this Step to initially read it from here and be able to Show the step accordingly based on the value that we have established here that is being the first problem after this we are going to see another problem that would be that when we update this thing that we already do here through the handling of events that magically or automatically is also established here and we have the advantages of the reactivity that we have here that is to say instead of giving it a manual click here so that the active changes Livewire does it as who says when this event is executed it could be seen in that way that is basically when the property that is here is updated So as I was telling you at the moment here we have two walls On the one hand we have alpine completely isolated from what Livewire is That is to say at least that is the exercise that we currently have but we need some way to mix both things and for that here we have the wire object that is the one that you can see here as soon as you start the documentation you can see that they introduce the Blessed wire up your nose as soon as you go down here you will see well we have this example and here they begin to talk to you about what It is the object in question in which as I mentioned before we can do many operations which are basically the ones you can see in this list
// Acceso a una propiedad de la clase componente de Livewire
$wire.foo
// Llamar a un método de la clase componente Livewire
$wire.someMethod(someParam)
// Llamar a un método de la clase componente de Livewire y hacer algo con su resultado
$wire.someMethod(someParam)
.then(result => { ... })
// Llamar a un método de la clase componente de Livewire y almacenar su respuesta usando async/await
let foo = await $wire.getFoo()
// Emitir un evento de la clase componente de Livewire llamado "algún evento" con dos parámetros
$wire.emit('some-event', 'foo', 'bar')
// Escuchando un evento Livewire emitido llamado "some-event"
$wire.on('some-event', (foo, bar) => {})
// Obtener una propiedad de Livewire
$wire.get('property')
// Establecer una propiedad de Livewire en un valor específico
$wire.set('property', value)
// Establecer la configuración de una propiedad de Livewire en un valor específico
$wire.set('property', value, true)
// Llamar a una función de Livewire
$wire.call('someMethod', param)
// Cargar un archivo y configurando la propiedad de Livewire
$wire.upload(
'property',
file,
finishCallback = (uploadedFilename) => {},
errorCallback = () => {},
progressCallback = (event) => {}
)
// Subir varios archivos y configurar la propiedad de Livewire
$wire.uploadMultiple(
'property',
files,
finishCallback = (uploadedFilenames) => {},
errorCallback = () => {},
progressCallback = (event) => {}
)
// Eliminando (uno de) los archivos cargados y actualizando la propiedad de Livewire
$wire.removeUpload(
'property',
uploadedFilename,
finishCallback = (uploadedFilename) => {},
errorCallback = () => {}
)
So I know that this part is a bit abstract you dont need to understand all of this were not going to use practically any of this to consult the property that we have defined there at the component class level but as much as I know its important that you understand that they exist And maybe at some point if we have to develop a particular project a particular component there we might need some things Here you can see that we can even do some things with it here but again what we need is simply a read and keep there as the full duplex command says so that when the State value is changed here on the server we can read it from here that would be the only thing were going to need but its important that you understand that at the moment we have something in Alpine on the one hand and something here in Livewire on the other hand and we havent mixed it yet so for this we have to initialize this value as I was telling you before with whatever we have defined here which in this case is
<div class="flex" x-data="{ active: $wire.entangle('step') }">
<div class="flex mx-auto flex-col sm:flex-row">
<div class="step" :class="{ 'active': parseInt(active) == 1 }">
{{ __('STEP 1') }}
</div>
<div class="step" :class="{ 'active': parseInt(active) == 2 }">
{{ __('STEP 2') }}
</div>
<div class="step" :class="{ 'active': parseInt(active) == 3 }">
{{ __('STEP 3') }}
</div>
{{-- <div x-text="active"></div>
<div x-text="$wire.step"></div>
<div x-text="$wire.get('step')"></div>
{{ $step }} --}}
</div>
</div>
How do we do that lets start by understanding how we can read this property so that we can then take advantage of it to initialize our variables defined here for that as I mentioned to you for the fourth time we have the object called wire here we can print it to be able to visualize it so to be able to visualize some text in the pin here we have to use the attribute called xtext here we indicate what we want to see we can place it here perfectly to print what is the asset that we have here and well lets see here quickly pending that it is in the same code as I mentioned before there we would see a one lost in life here is this one that is here then well this would be again at 100 we are going to print using the dollar wir we place what we want to print again this is the iware form that we have to access any property that we have defined here and be able to read it from here well this is called St so here we place St without the dollar this is a form here we would see another one here you can change this if you want to put two so that it does not shock you so much here you can see that two and a one appear this two would be the one from alpine which does not It has nothing to do with Livewire and this would be in principle what we have here defined here you can also change it for example by placing a two at least momentarily and here appears an important two that I think I did not mention Although it was always indicated at the beginning of the course have your running here
npm run dev
so that it takes the changes automatically So what other way again what other way do we have to access these properties that we have here defined at the class level here we also have a variant the syntax that would be the get
$wire.get('step')
Here we put the name that would be step and finally we have the Laravel form that this has no doubt that referencing wave as we have done up to this point well in this case we have used the War model but also remember that we can print this without any problem and here see Anything there would appear with the type I have nothing selected and this is in create place it here for example the type I am going to place exactly what I have repeated like hell place a 5000 here is that it would look like 5000
class General extends Component
{
#[Validate('required|min:2|max:255')]
public $subject;
#[Validate('required')]
public $type;
***
So there is not much doubt with that since remember that I presented this to you before that we can also print the os model we can print any property that we have defined here what I mean then this would be the form of the arvel that has nothing to do with this but even if it is there it is so that it is also clear and here we see everything then remember that at least for now we have as who says suspended the creation part based on what we did here I know that you mentioned it but we are moving here in the St without the need to be creating records so this part is important that you have it defined like this to do these tests and understand how all this works whether you have it defined here and you do the return or whether you commented it and then you define the steps we are going to start to give it here click here Well before that I am going to reload I click and I do not know anything to see Ah I did not select the type I select the type I am going to click again and again
Okay here you can see that it is updating so we could try to finally initialize what we want to get to this asset with our W object which was what I had here in the exercise at the beginning like 20 minutes ago Ill show it to you quickly here and lets see what happens so here we finally have integration again in what we have here in Laravel on the component side with something here on the client and this something is being alpine lets see what happens at this point Well Im going to comment on this at least so that it doesnt generate noise there I go back here reload select company send here again send and well its not doing anything here Here you can see that it is initialized So why doesnt it work Lets go again so that it is understood a little better We are here we are in Step One Note that it is taking if here I put for example a two based on the condition that we made before and we reload here you can see that it is taking it here Remember that no matter how much this is it is not going to change it This is how it is how we do it we write here it is not going to change anything if you change the class here where we have it defined but for the rest it is not going to change anything therefore it is important that there are no errors and but here do not expect it to render what is the block of the X which are the attributes of alpine do not expect it to change absolutely anything of the definition that we already have but notice that if it is taking it the problem is so that it is understood a little more clearly The idea is that this x data is only executed when it is initialized and it no longer does any followup on this that we are placing here on the value that we are initializing something similar to what happens with the mount event that we defined before to initialize some things in our component as we did for example to see the save one the Index one I think it was to see here I found one for example the mount one that we used before to see if we are creating or we were editing Something similar happens here that is to say it is only executed once when the page is loaded and it leaves it there it is not used anymore therefore that synchronization is not maintained between what we are doing on the server side and with what we have on the client and that is what that is exactly happening there and it is a bit what I am starting to explain to you here that you do the example that we saw before although you can see that this does go away if you undo this there we will see the changes but the problem is the initialization that we have here as you can see since it is an initialization
$wire.get('step')
And it is not like who says reloaded taking the changes is a little what I tell you here do this exercise there I define what it was that we did based on what was explained and that here what we are doing is a dry initialization and then precisely to achieve this much desired communication to see the changes here in St we have to expand a special object called entangle that here does change the definition a little bit So this is the previous syntax I have not updated it since right now it is used in the following way it is part excuse the redundancy of the object called wire for the rest the syntax is practically the same and what it does is precisely that communication this you also have Here in Livewire to the pin down here is the deang object that allows us that synchronization So lets see how all this is eaten here you have the syntax lets go back here we place instead of this we place rectangle we place eangle the parentheses as if it were a function and what is the Well here pending with the quotes I used single quotes outside Well Im going to put double because in everything I put double so it was a a little more organized and here I use the simple one although you could also use the double ones here and thats it but since Im using the double ones in all the rest of the places well here we put What is the property that we want as they say observe which is called St Well now you know how this works and there is not much loss there we do this and look how it works without problem Then we achieve as they say that watch that we have now to observe here the property called step and that would be practically everything With that as they say you can see that the step by step is working and we can now conclude the integration between alpine and livewire
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter