0
votes

i have a component register and add event @submit.prevent inside the template by $emit , i tried to console.log on the inisde method component, it was works, but when on my main js, it does not work and nothing, but not error

this is my component example :

Vue.component("register", {
  props: {
    form: Object
  },
  template: `
  <div class="container">
    <div class="row">
      <div class="col-sm-4 offset-4">
        <form @submit.prevent="goRegister">
          <div class="form-group">
            <label for="username">username</label>
            <input type="text" class="form-control" id="usernameRegister" aria-describedby="emailHelp" placeholder="Enter username" v-model.trim="form.username" required>
</form>
    </div>
  </div>
</div>
  `,
  methods: {
    goRegister() {
      this.$emit("doRegister", this.form);
    }
  }
});

this is my parent on my html :

 <register v-on:do-register="handleRegister" :form="forms"> </register>

and on my vue main js

new Vue({
   data:{
   forms: {
      username: null,
      email: null,
      password: null,
      name: null,
      age: null
}
}, 
methods : {
    handleRegister() {
      console.log(this.forms.username);
    }
}
})

i tried to console that method handleRegister, but nothing happened and not error, is that something missing on my parent component ??

1

1 Answers

2
votes

Just rename the event you are emitting: VueJS does not convert between camelCase and kebab-case for emitted event names. If you want to listen to the do-register event, you need to emit the event as do-register and not doRegister:

this.$emit('do-register', this.form);

What if you still want to emit a doRegister event? In that case, you will need to emit it as an all-lowercase string.

Note that bound event names inline has to be case-insensitive, due to a limitation in HTML, where attribute names are case-insensitive—the browser actually converts it to lowercase. Therefore, if you still prefer to emit an event without using the kebab-case nomenclature, then you will need to do:

this.$emit('doregister', this.form);

And in the consuming parent's template, you will need to listen to the doregister event:

<register v-on:doregister="handleRegister" :form="forms"> </register>