webmasterdro
webmasterdro

Reputation: 224

Custom event in Vuejs2

I'm not understanding the Custom Event in Vuejs2.

I have a component named as user-navbar which contains a dropdown menu, when change I execute this method:

handleCurrentServerChange: function(name, zoneid, currency_name) {
    /* Code omitted */
    this.$emit('server-changed', { serverznid: zoneid });
},

Which emit an event called server-changed and I want to listen to this event in another component accounts-linked.

 <accounts-linked inline-template :server_data="server_data" @server-changed="handleServer">

When the event is emitted I should call the method handleServer. But isn't working. This is the method:

handleServer: function(value) {
                alert(value);
}

I got few errors

[Vue warn]: Property or method "handleServer" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.
[Vue warn]: Invalid handler for event "server-changed": got undefined

What am I doing wrong?

Upvotes: 0

Views: 1083

Answers (2)

exclsr
exclsr

Reputation: 3357

The server-changed event can only be caught in the parent of user-navbar, like this:

<template>
    <user-navbar @server-changed="handleServer"></user-navbar>
</template>

If accounts-linked is not the parent of user-navbar, you will want to use a non-parent-child communication strategy, as outlined in the Vue.js docs.

Upvotes: 1

webmasterdro
webmasterdro

Reputation: 224

Searching for what @exclsr mentionted I found this Jsfiddle and apply that on my code:

app.js

Vue.use({
install(V) {
    let bus = new Vue();
    V.prototype.$bus = bus;
    V.bus = bus;
}     
});

In the components:

this.$bus.$emit('server-changed', 1);
this.$bus.$on('server-changed', this.handleServer);

Working perfectly now! :)

Upvotes: 0

Related Questions