I have a basic question related to argument of a function.
when emitting an event from a child to a parent or when triggering a click event, I've seen in somme cases the add of $event as a parameter to a function and when removing it the code don't work as expected.
why is this $event needed ? and why in some cases is it used and in others not ? which is the difference ?
example where not used:
parent-component.vue
<div id="app">
<p>Count is: {{ count }}</p>
<HelloWorld @appendByOne="appendByOne()"/>
</div>
data() {
return {
count:0,
};
},
methods: {
appendByOne(){
this.count = this.count+1;
}
}
child-component.vue
<div>
<button @click="append()">Add 1</button>
</div>
methods: {
append(){
this.$emit('appendByOne');
}
}
example where is used:
<v-btn @click="saveText($event)"> apply </v-btn>
methods: {
saveText(event) {
//run this code
}
saveText
is not representative, @click="saveText($event)"
and @click="saveText"
are equivalent.
The explicit use of $event
is necessary when function signature is something different than 1 event argument, e.g. @click="saveTextForId($event, someId)"
. Also it can be used to avoid declaring a method, @click="$emit('eventName', $event)"
.