1

This is the scenarios. I have a Graph component that appears in the body of the page, where the user can make some changes.

I also have a Search component that appears in the header of the page.

The two are unrelated - Graph only appears in the body of this one page, while Search appears in the header of all pages. They belong to app.js, which is currently just this:

require('./bootstrap');

window.Vue = require('vue');

Vue.component('search', require('./components/Search').default);
Vue.component('graph', require('./components/Graph').default);
/* other components */

import PerfectScrollbar from 'vue2-perfect-scrollbar'
import 'vue2-perfect-scrollbar/dist/vue2-perfect-scrollbar.css'

Vue.use(PerfectScrollbar);

const app = new Vue({
    el: '#app',

    data : {



    },

    methods : {



    },

    mounted : function(){



    },

    computed : {



    }
});

Now, when the user changes the data in Graph, I am supposed to send that change to Search. It doesn't really matter what the data is, I just need to figure out the sending process.

So, how do I send something from Graph to Search? I've been trying to emit the change, but I have no idea how to capture it in Search. I've used emit before with child/parent components, but I can't find documentation on how to do it here.

Logically, I think it should go through app.js somehow, but I can't find the appropriate syntax.

2 Answers 2

2

In these cases you generally have two options.

The preferred method is to use Vuex, which gives your application a global state, which can be shared across your entire application. Making it easy to share data between components that have no direct relation.

The other option is to use an Event Bus, which gives you a way to listen and send events across your component. But this approach isn't considered best practice and should be avoided if possible.

If you want do want to go with an event bus, Vue recommends using mitt.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. If I'm reading the Vuex docs correctly, I can mutate the state in the store from my Graph component. But does that mean that I would need to store the data there instead of the Search component? Or can I emit from the store to Search after every mutation?
You're going to store the data in the Vuex store (state). Your Search component will then retrieve the data from the store. And because of Vue's reactivity, whenever you update the state from your Graph component, it will automatically be updated in the Search component
0

What you are looking for is called a centralized store or a State and Vuex is your answer.

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.