0

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
}

1 Answer 1

0

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)".

Sign up to request clarification or add additional context in comments.

8 Comments

what do you mean by not representative ?
I mean it has 1 event arg, so there is no difference between @click="saveText($event)" and @click="saveText"
what if I have more than 2 params ? this.$emit('appendByOne', this.txt1, this.txt2); ? how to get txt2 ?
In this case you can emit an object, $emit('appendByOne', { txt: this.txt1, txt2: this.txt2 }). Or an array, $emit('appendByOne', [this.txt1, this.txt2]). It depends on your case and the role of appendByOne whether you want to use multiple events for multiple values or emit them at once
is it really necessary to use $event within an inlive function ? check the following example where it is not used <v-btn :title="$t('paragraph')" @click="$emit('openParagraphEditor',this.paragraph.id)> </v-btn> ****&****<v-select v-model="option" :items="options" @click="$emit('optionsDisplayed')">
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.