Search code examples
vue.jsgoogle-chrome-extensionvuex

How to emit events from component to main instance usint $emit or vuex


I want to use my main vuejs instance to manage sockets.io connection and events. I have this code that works, but I have some problems to pass events from component to parent instance. The code is inside a chrome extension that use vuex, but I'm not familiar with vuex at the moment. How I can pass events between my main instance and child component? Someone has suggested me to use vuex, but it's divided in three files and I'm not able to understand for now how to obtain what I want.

<script>
  // child component 
  export default {
    data() {
      return {
        isRegistered: false,
        isConnected: false
      }
    },
    mounted() {
      this.$on('connected', function(event) {
        console.log(event)
      })
    },
    methods: {
      initRoom() {
        console.log('clicked!')
        this.$emit('openConnection')
      }
    }
  }
</script>
// main instance
import Vue from 'vue'
import App from './App'
import store from '../store'
import router from './router'
import VueSocketIOExt from 'vue-socket.io-extended';
import io from 'socket.io-client';

const socket = io('https://lost-conn.herokuapp.com', {
  autoConnect: false
});

Vue.use(VueSocketIOExt, socket, { store });

/* eslint-disable no-new */
new Vue({
  el: '#app',
  store,
  router,
  render: h => h(App),
  mounted() {
    this.$on('openConnection', function() {
      socket.open()
      alert('k')
    })
  },
  data: {
    isRegistered: false,
    isConnected: false,
    message: ''
  },
  sockets: {
    connect() {
      console.log('socket connected')
      this.$emit('connected', 'socket connected')
    },
  },
  methods: {}
})

Solution

  • So, you can try vuex but it seems kind of heavy if all you want is a basic event listener. One option might be to go with the eventBus route and set up an emitter and a listener event. in main.js you can add

    export const eventBus = new Vue()
    

    Then in your code you could swap this.$emit('connected', 'socket connected')

    with eventBus.$emit('connected', true_or_any_other_value_here)

    Then in your component that you're listening for the event. Import eventBus from main.js and add:

    data: ( => ({ bus: eventBus }),
    
    created() {
        this.bus.$on('connected', ($event) => myCallbackFunction($event) )
    },
    

    I think this should do the trick, I haven't yet tried the callback function and passing data as I usually do my check on the front end but if there is data object you need to store please specify and I might be able to help you through using vuex.