Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can $on listener in a component listen for an $emit from mixin?

I'd like my global mixin to broadcast data to various components. Trying to listen for the custom event from the created (or mounted) event inside the component doesn't seem to work. eg.

in mixin ...

methods:  
   foo: function() {
     this.$emit('my-change','bar')
   } 

in component ...

created () {
  this.$on('my-change', function (e) {
    // do something 
  })
}

Is this possible?

like image 759
Peter S Avatar asked Mar 30 '18 09:03

Peter S


People also ask

Can a mixin use another mixin?

Whenever a mixin is defined inside another mixin, it can be used as return value too.

What is the benefit of using Mixins in Vuejs?

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component's own options.

What does $emit do in Vue?

Vue $emit is a function that lets us emit, or send, custom events from a child component to its parent. In a standard Vue flow, it is the best way to trigger certain events.

How do you emit event from child to grandparent in Vue?

To emit event from grandchild to his grandparent component with Vue. js, we call $emit in the grand child component. Then in the parent component, we pass the events from the child to the grandparent with v-on="$listeners . And then we listen to the event emitted from the grandchild component in the grandparent.


1 Answers

It all depends on the component nesting level, let's assume you have the following component structure, parent and a child component (and mixin, of course).

Parent.vue (you listen for the incoming event changes here):

private created(): void {
  this.$on('event', (value: boolean) => {
    console.log(value)
  })
}

And you have injected your mixin in a parent component:

private someRandomMethod(): void {
  this.$emit('event', true)
}

This would work, because your mixin is directly injected to a Parent.vue, so "Parent" component itself would be emitting an event. But if you've injected mixin in a "Parent" component, one level deeper (Parent > Child), you would need to emit like this:

this.$parent.$emit('event', true)

$parent makes your emit one level higher.

Also instead of using event Bus, you can use $root instance, so you have to listen it, like this.$root.$on, and emit it from mixin this.$root.$emit()

like image 103
Alexander Kim Avatar answered Oct 16 '22 17:10

Alexander Kim