What is the best method for exchanging data between two Vue instances?

index.html

<script defer src='main.js'></script>
<script defer src='extension.js'></script>

<div id='main-app'></div>
<div id='extension'></div>

main.js

const store = new Vuex.Store({
    state:{
        greeting:'hello'
    }
})

const mainApp = new.Vue({
    el:'#main-app',
    store
})

extension.js

const extension = new.Vue({
   mounted(){
       console.log('How can I access the greeting in the store?')
   }
})

I aim to utilize Vuex to fetch data from Vue instances imported from diverse files. This approach is necessary as each page has distinct plugins that load dynamically.

However, accessing app's state using rootState appears challenging due to different roots. Is there a workaround to retrieve the data like leveraging windows, mixins, or other global objects or methods?

Answer №1

If you are looking for a way to share state, localStorage is an option. However, if your goal is to pass data between components, using an event emitter and listener can be more suitable. The window object provides an Event API that allows you to achieve 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)
    }
  }
}

It's important to note that the code provided fulfills the specific requirement mentioned. Remember to detach any listeners when necessary (e.g., rootB.beforeDestroy()).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The absence of text is not displayed in an empty slot of a Buefy table

Currently, I am working on a Nuxt project with Buefy implementation. I attempted to create a table with an #empty slot that displays a message when no data is available. However, my code does not seem to be working as expected. If you refer to the Buefy do ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...

VueJS does not update values instantly as they change

I have implemented a JS class with the following code: class Field { public Value = null; public Items = []; public UniqueKey = null; public getItems() { let items = [...this.Items]; items = items.filter((item) => { ...

An object will not be returned unless the opening curly bracket is positioned directly next to the return statement

compClasses: function() { /* The functionality is different depending on the placement of curly brackets */ return { major: this.valA, minor: this.valB } /* It works like this, please pay attention to ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

What are some tips for utilizing the "bottom-row" slot within the "b-table" component in bootstrap-vue?

I am working on a component that utilizes the bootstrap-vue b-table component. My goal is to create a bottom row that displays the sum of each column in the table. However, I encountered an issue where the bottom-row only fills the first column, leaving ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

Troubleshooting VueJS, Electron, and Webpack integration with Hot Reload feature

I have been immersed in a new project that involves utilizing Electron, VueJS, and Webpack for HMR functionality. Unfortunately, I am encountering difficulties with the Hot Module Replacement feature not working as expected. Here is my current configurati ...

Vue js for filtering and replacing prohibited words

For this scenario, our objective is to screen the words in our input: <input type="text" class="form-control" placeholder="Write something..." v-model="todoInput""> Below are the restricted words that we aim to substitute in the input "restrict ...

What is the best way to calculate the number of days between today's date and the end of the current month using Moment.js?

Here's the current code snippet I am working with: const moment = require('moment') const m = moment const currDay = m().format('D') const dayOfWeek = m().format('dddd') const daysInMonth = m().daysInM ...

How can you specify the environment in Google Tag Manager?

I have integrated google tag manager and google analytics using the vue-gtm plugin found at vue-gtm Within google tag manager, I have set up 3 environments under the same container. In a user-defined variable called GA from environment, I have created a ...

Exploring the possibilities of utilizing classes in testing scenarios with Vue, Cypress, and Cucumber

I am currently working on setting up e2e tests using Cypress and Cucumber for my project. The application is built with Vue CLI 4.1.1, and I have added the package cypress-cucumber-preprocessor (V1.19.0) via NPM. Update: After extensive research and tes ...

The return value from vue-query is ObjectRefImpl, not the actual data

Greetings to the Vue.js community! As a newcomer to Vue.js, I am seeking guidance on fetching data using vue-query, Vue.js 3, and the composition API. The data returned to me is ObjectRefImpl, but when I try to print the values, I encounter the error: "Pro ...

What seems to be the issue with the data initialization function not functioning properly within this Vue component?

In my Vue 3 component, the script code is as follows: <script> /* eslint-disable */ export default { name: "BarExample", data: dataInitialisation, methods: { updateChart, } }; function dataInitialisation() { return { c ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Organizing a Vue.js SPA project: Implementing Vuex store and API calls efficiently

Here is how I have organized the structure of my Vue app: components/ article/ AppList.vue common/ AppObserver.vue NoSSR.vue layout/ AppFooter.vue AppHeader.vue ui/ AppButton. ...

An unconventional web address was created when utilizing window.location.hostname

I've encountered an issue while trying to concatenate a URL, resulting in unexpected output. Below you'll find the code I tested along with its results. As I am currently testing on a local server, the desired request URL is http://127.0.0.1:800 ...

Error: Vuex commit fails due to JSON circular structure issue

Using Vue.js along with the vuex store, I make an API call to validate an item, which returns arrays of errors and warnings. Below is my vuex action : export function validateitemReview ({ commit, dispatch, state }, { reviewId, type, itemreviewData }) { ...

Verify if the item already exists in the Vue.js array

Here is the data I have: data: function() { return { conversations: [ ] } } I am retrieving my data from the response object using response.data.conversation Is there a method to verify if this.conve ...