admin管理员组

文章数量:1404612

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;
      }
    }  

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
}

Share Improve this question asked Mar 10 at 16:51 ftouh yahamftouh yaham 53 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 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)".

本文标签: vuejscases for using event as param of a functionStack Overflow