0

I had a Vue question as part of a technical test that I couldn't get my head around.

The task was to create a small login form (username and password) and send the username and password as arguments to the submit function but using the $emit method.

However the question didn’t involve creating any component, so why would you use $emit if you are not passing properties from a child component to a parent? As far as I understand that's the whole purpose of $emit? Can you use emit within a parent element directly? I tried to do so. But couldn't make it work.

My attempt here:

<template>
  <div>
     <form @submit.prevent="$emit('login', this.username, this.password)">
      <input id="username" name="username" type="text" v-model="username">
      <input id="password" name="password" type="password" v-model="password"> 
      <button type="submit">Submit</button>
     </form>
  </div>
</template>

<script>
export default {
  name: "App",
  data: function () {
    return {
      username: "",
      password: "",
    }
  },
  methods: {
    login(arg1, arg2) {
      console.log(arg1)
      console.log(arg2)
    }
  },

};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
octavemirbeau
  • 481
  • 6
  • 19
  • 2
    These types of questions are common in order for you to display your architectural knowledge. You are not required to know about the parent component implementing the child component you're creating, just that you're creating re-usable code that others can adapt to. In the context of a single component, the `$emit` wouldn't make and sense and would require you to hook into the Vue constructor its self to access the parent element in order to listen to it, which is a horrible practice. – Ohgodwhy May 14 '21 at 20:25
  • See https://stackoverflow.com/questions/3987391/why-people-use-message-event-buses-in-their-code . It can be used in several components, including a component that owns event bus. The latter is an antipattern, not supported in Vue 3. It won't be workable as is any way because there's no `login` listener, and `login` method is unrelated. – Estus Flask May 15 '21 at 06:13

0 Answers0