Reputation: 68482
I was using the event emitter from vue to make the main app talk to the components and it was working as long as I had the app and all the components in one .js file.
But now I wish to have them separated, one component per file, and obviously I cannot use the event emitter anymore, because the app
appears undefined in the modules.
What do I need to change to be able have the app and components communicate again?
My code:
my-app.js
import My from '/my-module.js';
const app = new Vue({
router: new VueRouter({
mode: 'history',
routes: [{
path: '/',
component: My,
}]),
methods: {
created(){
this.ws = new WebSocket(...);
this.ws.onmessage = event => {
this.$emit('message', e);
}
}
}
}).$mount('#app');
my-module.js
export default {
template: `....`
created(){
// I want to be able to access 'app' here
// or another way to receive the messages
console.log(app);
app.$on('message', ...)
}
}
As you can see I only need this because I'm using websockets and the app holds the websocket client. The components need to do something when certain messages are received.
Upvotes: 1
Views: 736
Reputation: 1357
In your case, you may use those events in multiple components, specialy when app is still growing. i think you better use eventbus
to emit
and catch
all of them.
here how to use eventbus
in vuejs : https://alligator.io/vuejs/global-event-bus/.
in you're case :
import { eventBus } from 'path/to/file';
...
methods: {
created(){
this.ws = new WebSocket(...);
this.ws.onmessage = event => {
eventBus.$emit('message', e);
}
}
}
Other component :
import { eventBus } from 'path/to/file';
...
created() {
eventBus.$on('message',() => ) {
// code
}
}
Upvotes: 1