简体   繁体   中英

Share data between unrelated components in Vue.js

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM