Vuejs - Cannot read property '$on' of undefined at Component created

Viewed 227

I want to share a data between two components without update or communicate with parent component. I initialized const of Vue on my main.js - so now I can communicate between components
Gets error : "TypeError: Cannot read property '$ on' or undefined".

Can you explain please where I am wrong?

main.js

export const events = new Vue()

ComponentA:

<template>
  <div>   
    <button @click="editAge">Edit age</button>
  </div>
</template>

<script>
import events from "../../main.js";
export default {
  props: {
    age: {
      type: Number,
    },
  },

  methods: {
    editAge() {
      this.age += 5;
      // this.$emit("ageWasChanged", this.myAge);//if communicate through Parent comp
      events.$emit("ageWasChanged", this.age);
    },
  },
};
</script>

ComponentB

 <p>{{ age }}</p>

<script>
import events from "../../main.js";
export default {
  props: {   
    age: Number,
  },   
  created() {
    events.$on("ageWasChanged", (data) => {
      this.age = data;
    });
  },
};
</script>
2 Answers

Try putting your listener in mounted() instead of created()

mounted () {
  events.$on("ageWasChanged", (data) => {
    this.age = data;
  });
}

Are ComponentA and ComponentB sibling components or Parent and Child?If they are not, you can not use emit to communicate between components.

Related