We know both the below codes show the same result, but what are their differences? Can someone explain it? Thank you.
<button @click="$event.target.innerHTML = 'Hello World!'">Replace me with "Hello World!"</button>
<button @click="$el.innerHTML = 'Hello World!'">Replace me with "Hello World!"</button>
2
Answers
From the documentation:
event.target
i.e. it will return the element that triggered the action, in this case it is the button that you clicked.
$el
i.e. it will also select the element that triggered the action.
They do appear to do the same thing but Alpine provides a more concise reference to the current object.
In your examples it’s the same thing, $el result as a shortcut for $event.target, but you can use $el also outside of an event, for example I have a blade component like this:
where data-rel-option is set by the backend but is used by Alpine via $el