mx_code
mx_code

Reputation: 2517

How to listen to child events created programatically in vue js?

I've two components a child and a parent.

I'm instantiating the child in the parent manually & mounting it manually.

This is because My child component is rendereless and it doesn't have a tag like <app-child></app-child> which I can use it to instantiate in the template.

NOTE THAT HERE I'M NOT BINDING TO PROPS AND LISTENING TO EVENTS IN A REGULAR MANNER AS IN THE VUE - TEMPLATE BINDING AND LISTNENING

Here I'm not dealing anything with the template.

SO I will have to pass props and listen to events as given below.

But the issue is that even though I'm emitting event from child and listening it inside the parent. I'm not seeing any sign of it.

thought I'm listening to child event in parent as given below... I'm not getting any response from the event.

this is the parent

import { Child } from "./components/child";
import store from "@/store";

export default {
  name: "parent",
  components: {},
  props: [],
  data() {
    return {
      child: null,
    };
  },
  computed: {},
  created() {
    this.child = new Child({
      store,
      parent: this,
      propsData: {
        item: 'one' /// I'm being able to pass props and receive them in the child component
      },
    }).$mount();
    this.child.$on("hello", (e) => console.log(e, "yes")); // this is not working.
  },
  mounted() {
  },
  methods: {},
};

this is the child emitting event... 'hello'

import Vue from "vue";

const CHILD = {
  name: "child",
  components: {},
  props: ["item"],
  data() {
    return {};
  },
  render() {
    return null;
  },
  computed: {},
  created() {
    
  },
  mounted() {
    this.$emit('hello', 'parent')  /// this is child emitting event. this should be caught by the parent..
  },
  methods: {},
};

export const Child = Vue.extend(CHILD);

How can I solve this?

Upvotes: 2

Views: 1710

Answers (1)

Guru Prasad
Guru Prasad

Reputation: 4223

The event is firing as it should. The issue is that you're missing the event since you're registering your listener after the event already fired.

Try changing your parent component as follows:

  created() {
    this.child = new Child({
      store,
      parent: this,
      propsData: {
        item: 'one' /// I'm being able to pass props and receive them in the child component
      },
    })
    this.child.$on("hello", (e) => console.log(e, "yes")); // Set up listener before event will be fired
    this.child.$mount();
  }

Here's an example of it working: https://codepen.io/gurupras/pen/qBNWbag

Upvotes: 3

Related Questions