Home > OS >  Vuejs $emit doesnt work in some part of a function, and in other part works
Vuejs $emit doesnt work in some part of a function, and in other part works

Time:05-12

I am using vuejs3 and trying to emit event from a child component.

child Component

<input type="button" v-if="edition_mode" @click="cancel()"  value="Annuler">
[...]
cancel(){
    if(this.new_sav){
        this.$emit('test')
    }else{
        console.log('else')
        this.$emit('test')
    }
},

Parent Component

<div v-if="creation_form">
    <h4>Ajout Nouveau Sav</h4>
    <sav-form
    :initial_data="null" 
    :li_product="li_product" 
    :new_sav="true" 
    :customer_id="data.customer.id"
    @action="form_action"
    @test="test()"/>
</div>
[...]
test(){
    console.log('test emit works')
}

When cancel() is executed, in the if case $emit() works correctly, but in the else case, only 'else' is printed and $emit is not executed. What I am doing wrong here ?

I also have several buttons in child component, in the same div, that all call differents function but some function 'can' emit event and other can't.

CodePudding user response:

I am not sure what issue you are facing but it is working fine in the below code snippet. Please have a look and let me know if any further clarification/discussion required.

Demo :

Vue.component('child', {
  template: '<div><button @click="cancel()">Trigger emit event from child!</button></div>',
  data() {
    return {
        isValid: true
    }
  },
  methods: {
    cancel: function() {
      this.isValid = !this.isValid;
      if (this.isValid) {
        console.log('valid');
        this.$emit('test');
      } else {
        console.log('not valid');
        this.$emit('test')
      }
    }
  }
});

var vm = new Vue({
  el: '#app',
  methods: {
    getTestEvent() {
      console.log('Emit event from child triggered!');
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
    <child @test="getTestEvent"></child>
</div>

  • Related