drake035
drake035

Reputation: 2897

How to add emit information to a component dynamically generated using Vue.extent()?

I'm dynamically generating instances of my child component "Action.vue" using Vue.extent() this way:

let ActionClass = Vue.extend(Action)
let ActionInstance = new ActionClass({
  store
})
ActionInstance.$mount()
this.$refs.actions.appendChild(ActionInstance.$el)

This works fine. However, besides access to the store, child component also needs to emit an event (in response to user interaction with one of its elements) for the parent component to execute a method.

How to achieve this?

Upvotes: 1

Views: 1521

Answers (2)

Jack Van der bilt
Jack Van der bilt

Reputation: 111

https://v2.vuejs.org/v2/guide/components-custom-events.html https://v2.vuejs.org/v2/api/#Options-Lifecycle-Hooks

You can use a lifecylce hook (for example: mounted) to emit the event when the child has been created. you can listen to the events as documented in the documentation.

the store can be reached through this.$store.

Upvotes: 0

Eldar
Eldar

Reputation: 10790

You can use instance.$on method to add eventListenersdynamically :

Consumer

import Dummy from "./Dummy.vue";
import Vue from "vue";
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  methods: {
    mount: function() {
      const DummyClass = Vue.extend(Dummy);
      const store = { data: "some data" };
      const instance = new DummyClass({ store });
      instance.$mount();
      instance.$on("dummyEvent", e => console.log("dummy get fired", e));
      this.$refs.actions.appendChild(instance.$el);
    }
  }
};

Child component

export default {
  methods: {
    fire: function() {
      console.log("fired");
      this.$emit("dummyEvent", { data: "dummyData" });
    }
  }
};

Here is the Sandbox

Upvotes: 2

Related Questions