[Vuejs]-How to send and receive data between two Vue roots?

0👍

If you want ‘shared state’ you can use localStorage, sure, but your question asks more about ‘passing’ data. In this case you can use an event emitter and listener. Since window has an Event Api you can do it like this:

// rootA - emitter
{
  methods: {
    emitDataToComponentB (a, b, c) {
       const event = new CustomEvent('someEvent', { ...arguments })
       window.dispatchEvent(event)
    }
  }
}

// rootB - listener
{
  created () {
    this.listen()
  },

  methods: {
    listen () {
      window.addEventListener('someEvent', (args) => {
        console.log('@someEvent', args)
    }
  }
}

note: Only code required to meet the need shown. You’d want to make sure you detach any listeners at an appropriate time (eg rootB.beforeDestroy())

Leave a comment