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?
Whenever a mixin is defined inside another mixin, it can be used as return value too.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With