[Vuejs]-Why this.$listeners is undefined in Vue JS?

0👍

You have to understand what $listeners are.

this.$listeners will be populated once there are components that listen to events that your components is emitting.

let’s assume 2 components:

child.vue – emits an event each time something is written to input field.

<template>
    <input @input="emitEvent">
    </input>
</template>

<script>
export default {
  methods: {
    emitEvent() {
      this.$emit('important-event')
      console.log(this.$listeners)
    }
  }
}
</script>

parent.vue – listen to the events from child component.

<template>
  <div class="foo">
    <child @important-event="doSomething"></child>
  </div>
</template>

<script>
import child from './child.vue'

export default {
  data() {
    return {
      newcomment: {
        post_id: 'this is default value'
      }
    }
  },
  components: { child },
  methods: {
    doSomething() {
      // do something
    }
  }
}
</script>

With this setup, when you type something to the input field, this object should be written to the console:

{
    `important-event`: function () { // some native vue.js code} 
} 

-2👍

I added the following alias to my webpack.config.js file and this resolved the issue for me:-

    resolve: {
        alias: {
            'vue$': path.resolve(__dirname, 'node_modules/vue/dist/vue.js')
        }
    },

Leave a comment