1

I want to give data from one component to another. Therefore the first component should emit the BusEvent when Data is updated. The updated function is called, but I always get an Error in my console: Error in updated hook: "TypeError: Cannot read property '$emit' of undefined"

The other component also doesn´t receive height/width. And I get the same error here: TypeError: Cannot read property '$emit' of undefined.

I just started learning vue and I don't understand whats wrong. Thanks a lot for your help!

height and width are getting initialized in component one, so that can't be the problem.

//Definition of EventBus in main.js file
export const EventBus = new Vue(); 

//First Component
import EventBus from '@/main.js'
export default {
  data: function () {
    return {    
      height: '',
      width: ''
    }
  },

  updated() {
    EventBus.$emit('emited', this.height, this.width);
  }
}


//Second Component
import EventBus from '@/main.js'
export default {
  data: function () {
    return {
      height: '',
      width: ''
    }
  },

  mounted() {
    const self = this
    EventBus.$on('emited', function (height, width) {
      alert('WORKS!')
      self.height = height
      self.width = width
    })
  }
}

3
  • 2
    How did you define your EventBus in main.js? Commented Jun 11, 2019 at 10:02
  • I did it like that: export const EventBus = new Vue(); Commented Jun 11, 2019 at 10:08
  • 1
    You should import it like import { EventBus } from '@/main.js' then Commented Jun 11, 2019 at 10:17

1 Answer 1

2
  1. EventBus should be imported like this import { EventBus } from '@/main.js'

  2. If you want to pass multiple values via $emit you should use object.

Replace

EventBus.$emit('emited', this.height, this.width);

with

EventBus.$emit('emited', {height: this.height, width: this.width});

and then for listener:

EventBus.$on('emited', function ({height, width}) ...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.